Vector Semantics and Embeddings

Search engines, recommenders and RAG pipelines all compare meaning by comparing vectors. This guide builds those vectors from the ground up: counts and cosine similarity, TF-IDF and BM25 worked by hand, PMI, word2vec, GloVe and fastText, then the contextual embeddings modern retrieval runs on.

Every system that searches, ranks or groups text by meaning has to solve the same problem first: computers compare numbers, not words. Before a search engine can decide that a page about automobiles answers a query about cars, or a RAG pipeline can find the passage that answers a question, each piece of text has to become a list of numbers, a vector, arranged so that closeness between vectors reflects closeness in meaning.

This guide builds those vectors from first principles. It starts with the linguistic idea that makes the whole field work, moves through the count-based methods that search engines still rely on (TF-IDF, BM25 and PMI), then the learned dense embeddings that replaced them in most of NLP (word2vec, GloVe and fastText), and finishes with the contextual and sentence embeddings that semantic search and retrieval augmented generation run on today. Every formula comes with a worked example you can check by hand, and the output printed in each code block is real.

Two ways to read this

New to the topic? Read it top to bottom; each section builds on the one before. Revising for an exam or an interview? Start with the formula sheet and the self-test questions at the end, then follow them back to anything that feels shaky. To see a search happen, open the vector search playground. This article is the companion to RAG Explained, whose indexing step turns documents into exactly these vectors.

The distributional hypothesis

Here is a word you have probably never seen: zarfle. Here are some sentences that use it:

  • She poured hot zarfle into her mug before the meeting.
  • Zarfle tastes bitter unless you add milk and sugar.
  • He gave up zarfle because it kept him awake at night.

You still could not define zarfle precisely, but you can guess a great deal: it is a drink, probably hot, probably caffeinated, something like coffee or tea. You worked that out from nothing but the words around it.

That intuition has a name: the distributional hypothesis. Words that occur in similar contexts tend to have similar meanings. Linguists developed the idea in the 1950s, notably Martin Joos (1950), Zellig Harris (1954) and J. R. Firth (1957). Harris observed that synonyms such as oculist and eye-doctor turn up in almost the same environments, near words like eye and examined, and argued that the amount of meaning difference between two words corresponds roughly to the amount of difference in their environments. Firth put it most memorably: "You shall know a word by the company it keeps."

The rest of this article turns that idea into arithmetic. Describe each word by the company it keeps, as a vector of numbers, and words that keep similar company end up with similar vectors.

What a model of word meaning should capture

Before building vectors, it helps to know what we want them to capture. Lexical semantics, the branch of linguistics that studies word meaning, gives us a checklist: what words mean, how they relate to each other, and how context changes what they signify.

Lemmas and senses

A lemma is the dictionary form of a word: sing is the lemma of sang, sung and singing. Many lemmas are polysemous, meaning they have more than one sense: bank can be a financial institution or the land beside a river. Each of these meanings is a word sense. Keep polysemy in mind, because most of the methods in this article give each word exactly one vector, whichever sense a sentence uses. We come back to that problem near the end.

Synonymy and the principle of contrast

Two senses are synonyms when their meanings are identical or nearly so: car and automobile, water and H2O. Even synonyms are rarely perfect substitutes, though. You ask for a glass of water, not a glass of H2O, because H2O belongs to a scientific register. Linguists call this the principle of contrast (Girard 1718, Bréal 1897, Clark 1987): a difference in linguistic form is always associated with some difference in meaning. It is likely that no two words mean exactly the same thing, so synonymy is best treated as a matter of degree.

Similarity and relatedness

Most words have few synonyms but many similar words. Apple is not a synonym of pear, but the two are similar: both are fruit, both grow on trees, both end up in pies. Judging how similar two words are is the basis for judging how similar two phrases or sentences are, which question answering, paraphrase detection and summarization all depend on.

Relatedness, also called association, is a looser link. Coffee and cup are not similar, since one is a drink and the other a container, but they are clearly related: you drink one from the other. The distinction matters more than it looks. Count-based vectors tend to capture relatedness, and popular benchmarks differ on which of the two they measure, as the evaluation section shows.

Semantic fields and frames

Words that cover a particular domain and bear structured relations to each other form a semantic field: proton, orbital and wave function belong to quantum physics; waiter, menu, plate and chef to restaurants.

A semantic frame is the dynamic counterpart: a set of words that denote perspectives on, or participants in, a particular type of event. A commercial transaction has a buyer, a seller, goods and money, and English can describe it from the buyer's side (buy), the seller's side (sell) or the money side (pay), with nouns such as buyer and price for its participants. A system that knows the frame can tell that "Ana bought a book from Ben" and "Ben sold Ana a book" describe the same event. Fields group words that belong together; frames describe who does what to whom.

Connotation

Words also carry connotation: the feelings, opinions and evaluations attached to them. Innocent and naive can describe the same behavior, but one is a compliment and the other is not. In the 1950s Charles Osgood and colleagues asked people to rate words on scales such as good to bad, strong to weak and active to passive, and found that three dimensions accounted for most of the variation. Osgood called them evaluation, potency and activity; today they are usually named:

  • Valence: the pleasantness of the stimulus.
  • Arousal: the intensity of the emotion it provokes.
  • Dominance: the degree of control it exerts.
WordValenceArousalDominance
courageous8.055.507.38
music7.675.576.50
heartbreak2.455.653.58
cub6.713.954.24
innocent6.554.405.92
naive4.223.865.00

These scores, on a scale from 1 to 9, come from Warriner, Kuperman and Brysbaert's 2013 norms for 13,915 English lemmas. Look at what the table does: it turns every word into three numbers, a point in three-dimensional space. Courageous and music sit near each other; heartbreak sits far from both; innocent is about two points more pleasant than naive. Representing a word as a point in space is the first of the two ideas behind vector semantics.

Vector semantics: meaning of a word as a point in space

Vector semantics combines two ideas from the 1950s: Osgood's, that a word's meaning can be a point in a multidimensional space, and the distributionalists', that a word's meaning can be defined by its distribution, the neighboring words and grammatical environments it occurs in. Put together, they give the standard way NLP represents meaning: a word is a point in a semantic space, and its coordinates are derived from the contexts it appears in. Vectors for representing words are called embeddings.

Why go to the trouble? Consider a sentiment classifier trained on reviews. If it represents words as plain symbols, it can only use words it saw in training: having learned that terrible signals a bad review, it knows nothing about awful. If words are embeddings, awful lands near terrible, and the classifier can generalize to it.

There are two families of embedding, and this article covers both.

  • Sparse, count-based vectors

    Long, with one dimension per vocabulary word (often tens of thousands), mostly zeros, and built by counting. TF-IDF, BM25 and PPMI belong here. Every dimension is a word you can read off.

  • Dense, learned vectors

    Short, typically a few hundred to a few thousand dimensions, every value a real number, and learned by training a model. Word2vec, GloVe, fastText and transformer encoders belong here. No single dimension has an obvious meaning.

Figure 1. A sparse count vector and a dense embedding. The values are illustrative.

Words and documents as vectors

The term-document matrix

The simplest way to turn text into vectors is a term-document matrix: one row for every word in the vocabulary, one column for every document, and in each cell the number of times that word occurs in that document. Here are four words in four of Shakespeare's plays:

WordAs You Like ItTwelfth NightJulius CaesarHenry V
battle10713
good114806289
fool365814
wit201523

Read down a column and you get a document vector: As You Like It is [1,114,36,20] and Henry V is [13,89,4,3]. A vector is just a list of numbers, and a vector space is a collection of vectors with a fixed number of dimensions. These vectors have four dimensions because we picked four words; in a real term-document matrix, each document vector has one dimension per vocabulary word, ∣V∣ of them, and almost all of them are zero. Meaning, if you list every word you know, and you're trying to count how many times each appears across each document, some words never appear at all, therefore most values will be zero since a document uses only a fraction of words and not all. ∣V∣ stands for vocabulary, which is a master word list containing every unique word across your entire collection of documents.

Term-document matrices were invented for information retrieval: finding the documents in a collection that best match a query. Similar documents use similar words, so their column vectors are similar too. Plot just two dimensions, fool and battle, and the comedies separate from the history and the tragedy:

Figure 2. Each play as a vector of two word counts. The comedies point along fool, the history and the tragedy along battle. Counts from Jurafsky and Martin, Speech and Language Processing.

Retrieval works the same way. Represent the query as a vector over the same ∣V∣ words, and rank the documents by how similar their vectors are to it. How to measure that similarity is the subject of the next section but one.

Words as vectors

Read across a row instead and each word becomes a vector whose dimensions are documents: battle is [1,0,7,13] and fool is [36,58,1,4]. Similar words have similar vectors because they tend to occur in the same documents. Fool and wit are both frequent in the comedies; battle is not.

The word-word matrix

A whole document is a coarse notion of context. A term-term matrix, also called a word-word or term-context matrix, uses the words around each occurrence instead. Its rows and its columns are both vocabulary words, so the matrix is ∣V∣×∣V∣, and each cell counts how often the column word (the context) appears near the row word (the target) in a training corpus. "Near" usually means inside a window, for example four words to the left and four to the right:

Targetaardvarkcomputerdataresultpiesugar
cherry028944225
strawberry00016019
digital01,6701,6838554
information03,3253,982378513

A real matrix has a column for every word in the vocabulary, most of them zero, like aardvark here. Cherry and strawberry share pie-and-sugar contexts; digital and information share computer-and-data contexts. Plot those last two on the data and computer dimensions:

Figure 3. Two words as vectors of how often they appear near data and computer. They point the same way; only their lengths differ. Counts from Jurafsky and Martin.

The two vectors point in almost the same direction, but information is more than twice as long, simply because it is a more frequent word. That observation decides how we should compare vectors.

Measuring similarity with cosine

To compare two vectors 𝐯 and 𝐰 with the same number of dimensions N, the natural starting point is the dot product:

𝐯⋅𝐰=∑i=1Nviwi=v1w1+v2w2+⋯+vNwN

It is large when the two vectors have large values in the same dimensions, and zero when they never overlap. As a similarity measure, though, it favors long vectors. The length (or norm) of a vector is

∥𝐯∥=∑i=1Nvi2

and frequent words have long vectors, because they co-occur with more words, more often. A raw dot product would rate information as more similar to almost everything than a rarer word, purely because it is common. We want a similarity that does not depend on frequency, so we divide by both lengths. The result is the cosine of the angle between the two vectors:

cos⁡(𝐯,𝐰)=𝐯⋅𝐰∥𝐯∥ ∥𝐰∥=∑i=1Nviwi∑i=1Nvi2 ∑i=1Nwi2

Equivalently, the cosine is the dot product of the two vectors after each has been scaled to length 1, which turns it into a unit vector, 𝐯/∥𝐯∥.

Figure 4. Cosine similarity reads only the angle between two vectors. Count vectors have no negative entries, so their cosine stays between 0 and 1.

The cosine runs from 1 for vectors pointing the same way, through 0 for vectors at right angles, to −1 for vectors pointing in opposite directions. Counts are never negative, so for count vectors it stays between 0 and 1.

Here is the calculation on three dimensions of the word-word matrix, pie, data and computer:

Wordpiedatacomputer
cherry44282
digital51,6831,670
information53,9823,325
cos⁡(cherry,information)=442⋅5+8⋅3982+2⋅33254422+82+22 52+39822+33252=40,716442.08×5187.68≈0.018
cos⁡(digital,information)=5⋅5+1683⋅3982+1670⋅332552+16832+16702 52+39822+33252=12,254,4812370.95×5187.68≈0.996

Digital and information point the same way, about 5 degrees apart; cherry is almost at right angles to information, about 89 degrees. And the result no longer says anything about information being the more frequent word: the cosine has normalized that away.

Cosine similarity in NumPypython
import numpy as np
 
def cosine(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
 
# Dimensions: pie, data, computer (co-occurrence counts)
cherry      = np.array([442,    8,    2])
digital     = np.array([  5, 1683, 1670])
information = np.array([  5, 3982, 3325])
 
print(round(cosine(cherry, information), 3))   # 0.018
print(round(cosine(digital, information), 3))  # 0.996

Cosine, dot product and Euclidean distance

Once every vector is normalized to length 1, the three common similarity measures rank neighbors identically. The dot product of two unit vectors is their cosine, and their squared Euclidean distance is ∥𝐚−𝐛∥2=2−2cos⁡(𝐚,𝐛), so a smaller distance always means a larger cosine. That is why the choice of metric in a vector database matters little for normalized embeddings, such as OpenAI's.

TF-IDF: weighting words by how informative they are

Raw counts are a poor measure of how much a word tells us about a document, because word frequencies are extremely skewed. Function words such as the, it and they occur everywhere and say almost nothing, and even a content word like good, which appears at least 62 times in every play in the Shakespeare table, is too common to tell documents apart. This creates a paradox. Words that occur often in a document matter, which is why we count them, but words that occur often in every document do not. TF-IDF resolves it by multiplying two numbers: one that rewards frequency within the document, and one that penalizes frequency across the collection. It is the standard weighting when the dimensions are documents, as in a term-document matrix.

Term frequency

The term frequency of term t in document d starts as a plain count, tft,d=count(t,d). Raw counts overstate differences, though: a word that appears 100 times is not ten times more relevant than one that appears 10 times. So the count is usually compressed with a logarithm, with zero handled separately because the logarithm of 0 is undefined:

tft,d={1+log⁡10count(t,d)if count(t,d)>00otherwise

One occurrence gives a weight of 1, ten give 2 and a hundred give 3. A common alternative is log⁡10(1+count(t,d)).

Inverse document frequency

The second factor gives higher weight to words that occur in only a few documents. A term confined to a handful of documents helps tell those documents apart from the rest; a term spread across the whole collection does not. The document frequency dft of a term is the number of documents it occurs in, not the total number of times it occurs. The inverse document frequency is

idft=log⁡10(Ndft)

where N is the number of documents in the collection. The fewer documents a word appears in, the higher its weight, and a word that appears in every document gets log⁡101=0. The logarithm compresses the range again, since N can run into the millions. Karen Spärck Jones introduced the idea in 1972 as a measure of term specificity, which, in her words, "can be quantified as an inverse function of the number of documents in which it occurs".

Across all 37 of Shakespeare's plays:

Worddfidf
Romeo11.568
salad21.267
Falstaff40.966
forest120.489
battle210.246
wit340.037
fool360.012
good370
sweet370

Romeo appears in a single play and gets the highest weight; good and sweet appear in all 37 and get none.

TF-IDF weights

The TF-IDF weight of a term in a document is the product of the two:

wt,d=tft,d×idft

Applied to the four-play matrix, using each word's idf from the full collection of 37 plays:

WordAs You Like ItTwelfth NightJulius CaesarHenry V
battle0.24600.4540.520
good0000
fool0.0300.0330.0120.019
wit0.0850.0800.0480.054

To check one cell: battle occurs 13 times in Henry V, so tf=1+log⁡1013=2.114; it appears in 21 of the 37 plays, so idf=log⁡10(37/21)=0.246; and 2.114×0.246=0.520. Good, the most frequent word in the table, now contributes nothing at all, while battle, the rarest, dominates.

TF-IDF in practice

For retrieval, the query and every document become TF-IDF vectors over the same vocabulary, and documents are ranked by their cosine with the query. Libraries vary the details. scikit-learn's TfidfVectorizer uses the raw count as tf, a smoothed natural-log idf, and normalizes every document vector to length 1:

idf(t)=ln⁡1+n1+df(t)+1

The ones in the fraction act as if one extra document contained every term once, which prevents division by zero, and the final +1 keeps a term that occurs in every document from being ignored entirely.

TF-IDF with scikit-learnpython
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
 
docs = [
    "the cat sat on the mat",
    "the dog sat on the log",
    "cats and dogs are pets",
]
vectorizer = TfidfVectorizer()      # raw counts, smoothed idf, L2-normalized rows
X = vectorizer.fit_transform(docs)  # sparse matrix: 3 documents x 12 terms
 
idf = dict(zip(vectorizer.get_feature_names_out(), vectorizer.idf_))
print(round(idf["the"], 3), round(idf["cat"], 3))  # 1.288 1.693
print(cosine_similarity(X).round(2))
# [[1.   0.63 0.  ]
#  [0.63 1.   0.  ]
#  [0.   0.   1.  ]]

The first two documents share the, sat and on, so their cosine is 0.63. The third shares nothing with either, not even with cat, because cats is a different string. Count-based vectors only match identical tokens. Stemming or lemmatizing the text first narrows the gap; dense embeddings close it.

BM25: the ranking function behind search engines

TF-IDF with cosine similarity works, but two of its assumptions are shaky. Its term-frequency part keeps growing: even with a logarithm, the fiftieth occurrence of a word still adds weight. And it does not model document length directly, so long documents, which contain more of everything, have an edge. BM25 fixes both, and it has been the default ranking function of full-text search for decades.

BM stands for best matching. Stephen Robertson, Steve Walker and colleagues developed it for the Okapi search system at City University London, and it first appeared in their runs for TREC-3, the 1994 Text REtrieval Conference, combining two earlier formulas, BM11 and BM15. It grew out of the probabilistic relevance framework that Robertson and Karen Spärck Jones developed in the 1970s; Robertson and Zaragoza's 2009 survey tells the full story. Today BM25 is the default similarity in Elasticsearch, and Apache Lucene, the library beneath Elasticsearch, OpenSearch and Solr, implements it with defaults of k1=1.2 and b=0.75.

The formula

For a query Q with terms q1,…,qn and a document D, BM25 adds up one contribution per query term:

score(D,Q)=∑i=1nIDF(qi)⋅f(qi,D)⋅(k1+1)f(qi,D)+k1⋅(1−b+b⋅∣D∣avgdl)
  • f(qi,D) is the term's frequency in the document: how many times it occurs there.
  • ∣D∣ is the document's length in words, and avgdl the average document length in the collection.
  • k1 controls how quickly term frequency saturates.
  • b, between 0 and 1, controls how strongly scores are normalized for document length.
  • IDF(qi) is the term's inverse document frequency, in BM25's own form, covered below.

Term-frequency saturation

Set the length part aside for a moment: for a document of exactly average length it equals 1, and the term-frequency part becomes tf(k1+1)/(tf+k1). As tf grows this rises quickly, then flattens out towards an upper limit of k1+1. However often a term repeats, its contribution is capped.

Figure 5. BM25 saturates term frequency. Each curve is tf(k1 + 1) / (tf + k1) for a document of average length; it approaches k1 + 1 (the dotted lines) however often the term repeats.

With the default k1=1.2, one occurrence scores 1.0, two score 1.375, five score 1.774 and twenty score 2.075, against a ceiling of 2.2. k1 sets the bend. At k1=0 the term-frequency part equals 1 for any count, so the formula only asks whether the term is present. As k1 grows large the curve straightens towards raw term frequency. Robertson and Zaragoza call this behavior saturation, and note that BM25's saturating function "has frequently been shown to work better than traditional tf*idf", whose term frequency is linear.

The (k1+1) factor in the numerator does not change the ranking, since it multiplies every score by the same constant. It is there so that a single occurrence in a document of average length weighs exactly its IDF; some published versions and implementations leave it out.

Document length normalization

Now the length part, often written B:

B=1−b+b⋅∣D∣avgdl

It multiplies k1 in the denominator. A document twice the average length has B=1.75 with b=0.75, so it needs more occurrences of a term to earn the same weight, while a short document needs fewer. The reasoning is that a long document mentions everything more often, so each occurrence is weaker evidence that the document is about the term. With b=1 normalization is full; with b=0 it is switched off.

BM25's IDF

BM25's IDF comes from the Robertson and Spärck Jones relevance weight. With no information about which documents are relevant, that weight reduces to

IDF(qi)=ln⁡N−n(qi)+0.5n(qi)+0.5

where N is the number of documents and n(qi) the number that contain the term. This form has a quirk: when a term occurs in more than half the documents, the fraction drops below 1 and the IDF turns negative, so matching a very common term would lower a document's score. Lucene, and therefore Elasticsearch, adds 1 inside the logarithm to keep it positive:

IDF(qi)=ln⁡(1+N−n(qi)+0.5n(qi)+0.5)

Other libraries handle it differently. The popular Python package rank_bm25, for example, keeps the original form and replaces negative values with a floor of 0.25 times the average IDF. Scores from different implementations are therefore not directly comparable.

BM25 by hand

Take a collection of N=1,000 documents with an average length of 100 words, the defaults k1=1.2 and b=0.75, and the query jaguar speed. Jaguar is rare, appearing in 10 documents; speed is common, appearing in 300:

IDF(jaguar)=ln⁡(1+1000−10+0.510+0.5)=4.557IDF(speed)=ln⁡(1+1000−300+0.5300+0.5)=1.203

Four documents, with their lengths and term counts:

DocumentLengthjaguarspeedScore
D1100115.761
D2100407.712
D3400405.077
D4100062.206

Each effect shows up in the ranking, D2, D1, D3, D4:

  • Saturation. D2 mentions jaguar four times and D1 once, yet D2's jaguar contribution is only 1.69 times D1's: 4.557×4×2.24+1.2=7.712. With a linear term frequency it would have been 4×4.557=18.23.
  • Length. D3 has the same four mentions as D2 but is four times as long, so B=0.25+0.75×4=3.25, and its score falls from 7.712 to 4.557×8.84+1.2×3.25=5.077.
  • Rarity. D4 mentions speed six times and still ranks last: six mentions of a common term are worth 1.203×13.27.2=2.206, less than a single mention of the rare one.
BM25 from scratchpython
import math
from collections import Counter
 
def bm25_scores(query, docs, k1=1.2, b=0.75):
    """Score every document (a list of tokens) against the query tokens."""
    N = len(docs)
    avgdl = sum(len(d) for d in docs) / N
    df = Counter(term for d in docs for term in set(d))
    scores = []
    for d in docs:
        tf = Counter(d)
        length_norm = 1 - b + b * len(d) / avgdl
        score = 0.0
        for term in query:
            if tf[term] == 0:
                continue
            idf = math.log(1 + (N - df[term] + 0.5) / (df[term] + 0.5))
            score += idf * tf[term] * (k1 + 1) / (tf[term] + k1 * length_norm)
        scores.append(score)
    return scores
 
corpus = [
    "the jaguar is a big cat native to the americas",
    "jaguar jaguar jaguar fan forum",
    "the jaguar car has a top speed of 200 mph",
    "speed limits and speed cameras on the motorway",
]
docs = [doc.split() for doc in corpus]
print([round(s, 3) for s in bm25_scores("jaguar speed".split(), docs)])
# [0.328, 0.612, 0.966, 0.961]

The third document, the only one with both terms, ranks first. The fourth comes a close second, because in this tiny collection speed, found in two documents, is rarer than jaguar, found in three. Run the same documents through rank_bm25's BM25Okapi and the fourth scores 0: speed appears in exactly half of them, so the original IDF is ln⁡(2.5/2.5)=0, and jaguar goes negative until the floor lifts it. Small collections expose these edge cases; in a large one, few query terms appear in more than half the documents.

Tuning and variants

Robertson and Zaragoza report that values around 0.5<b<0.8 and 1.2<k1<2 are reasonably good in many circumstances, while noting that the best values depend on the documents and queries. If you have relevance judgments for your own data, tune on them. Several variants are in common use:

  • BM25F handles documents with fields, such as a title, a body and anchor text, by weighting and length-normalizing each field separately and applying saturation once, to the combined frequency.
  • BM25L and BM25+, both available in rank_bm25, adjust the term-frequency normalization so that very long documents are not penalized too heavily.

Why BM25 still matters

Dense embeddings have not made BM25 obsolete. On BEIR, a benchmark of 18 datasets that tests retrieval models on domains they were not trained for, Thakur and colleagues (2021) found that "BM25 is a robust baseline", while dense retrievers, though computationally efficient, often underperformed. Exact matching also matters for names, product codes and error messages that an embedding model may never have seen. That is why many production RAG systems run BM25 and a dense retriever side by side and merge the two ranked lists, for example with reciprocal rank fusion.

Pointwise mutual information

TF-IDF suits term-document matrices. When the dimensions are context words, as in the word-word matrix, the standard weighting is pointwise mutual information (PMI). Its intuition is that the best way to measure the association between two words is to ask how much more often they occur together in a corpus than we would expect by chance:

PMI(w,c)=log⁡2P(w,c)P(w) P(c)

The numerator is how often target w and context c are actually observed together. The denominator is how often we would expect them together if they were independent, since the probability of two independent events both happening is the product of their probabilities. The ratio is how much more often than chance they co-occur. The measure comes from information theory (Fano, 1961); Kenneth Church and Patrick Hanks (1990) brought it to word association, reporting for example that the five words most associated with doctor in their corpus were dentists, nurses, treating, treat and hospitals.

PMI ranges from negative infinity to positive infinity. A negative value claims that two words occur together less often than chance, which is hard to establish reliably without an enormous corpus. So in practice negative values are replaced with zero, giving positive PMI:

PPMI(w,c)=max⁡(log⁡2P(w,c)P(w) P(c),  0)

PPMI by hand

The probabilities are estimated from counts. Here is the word-word table again, with each row's and each column's total:

Wordcomputerdataresultpiesugarcount(w)
cherry28944225486
strawberry001601980
digital1,6701,68385543,447
information3,3253,9823785137,703
count(c)4,9975,6734735126111,716

With fij the count of word i with context j, every probability is a count divided by the grand total:

P(wi,cj)=fij∑i∑jfijP(wi)=∑jfij∑i∑jfijP(cj)=∑ifij∑i∑jfij

For information with the context data:

P(information,data)=3982/11716=0.3399P(information)=7703/11716=0.6575P(data)=5673/11716=0.4842PPMI(information,data)=log⁡20.33990.6575×0.4842=0.0944

The whole PPMI matrix:

Wordcomputerdataresultpiesugar
cherry0004.383.30
strawberry0004.105.51
digital0.180.01000
information0.020.090.2800

Cherry and strawberry are strongly associated with pie and sugar. Data is only mildly associated with information: information is so frequent that it co-occurs with nearly everything, so co-occurring with data is no surprise.

PMI's bias towards rare words

PMI has a known weakness: very rare words get very high values, because a few chance co-occurrences of rare words look like a strong association. Two fixes are common. The first raises the context counts to a power α<1 before turning them into probabilities, which gives rare contexts a higher probability than their counts alone, and so a lower PMI:

PPMIα(w,c)=max⁡(log⁡2P(w,c)P(w) Pα(c),  0)Pα(c)=count(c)α∑c′count(c′)α

Levy, Goldberg and Dagan (2015) found that α=0.75 works well, borrowing the value from word2vec's negative sampling, which is coming up shortly. In the table above it cuts the PPMI of the rarest context, sugar, from 3.30 to 1.80 for cherry, and raises the frequent context data from 0.09 to 0.23 for information. The second fix is add-k (Laplace) smoothing: add a small constant k to every count before computing PMI, which discounts all the non-zero values, and discounts them more the larger k is.

PPMI in NumPypython
import numpy as np
 
words    = ["cherry", "strawberry", "digital", "information"]
contexts = ["computer", "data", "result", "pie", "sugar"]
F = np.array([[   2,    8,   9, 442, 25],
              [   0,    0,   1,  60, 19],
              [1670, 1683,  85,   5,  4],
              [3325, 3982, 378,   5, 13]])
 
def ppmi(F, alpha=1.0):
    P = F / F.sum()                       # joint probabilities P(w, c)
    p_w = P.sum(axis=1, keepdims=True)    # P(w): row sums
    c = F.sum(axis=0) ** alpha            # context counts, smoothed when alpha < 1
    p_c = c / c.sum()                     # P(c), or P_alpha(c)
    with np.errstate(divide="ignore"):    # log2(0) is -inf; clipped to 0 below
        pmi = np.log2(P / (p_w * p_c))
    return np.maximum(pmi, 0)
 
print(ppmi(F).round(2))
# [[0.   0.   0.   4.38 3.3 ]
#  [0.   0.   0.   4.1  5.51]
#  [0.18 0.01 0.   0.   0.  ]
#  [0.02 0.09 0.28 0.   0.  ]]

From sparse to dense vectors

TF-IDF, BM25 and PPMI vectors are long, with ∣V∣ dimensions that often number in the tens of thousands, and sparse, with almost every value zero. The rest of this article is about short, dense vectors: a few hundred dimensions, every one a real number that may be negative, and no single dimension with a clear interpretation.

Dense vectors work better than sparse ones in almost every NLP task. Why is not completely understood, but there are good reasons to expect it:

  • Fewer weights. A classifier that takes 300-dimensional inputs has far fewer weights to learn than one that takes 50,000-dimensional inputs, and the smaller parameter space may help it generalize and avoid overfitting.
  • Synonymy. In a sparse vector, car and automobile are separate, unrelated dimensions, so a word that tends to appear near car and a word that tends to appear near automobile look different. Dense dimensions can capture what the two contexts have in common.

The first dense method came from linear algebra rather than learning. Latent semantic analysis (Deerwester and colleagues, 1990) applied singular value decomposition to a large term-document matrix and kept about 100 factors, so each document became a vector of around 100 weights instead of one count per word. The approach that dominates today learns the vectors through a prediction task instead.

Word2vec

Word2vec, from Tomas Mikolov and colleagues at Google in 2013, made dense embeddings fast and practical. The first paper introduced two architectures, continuous bag-of-words (CBOW) and skip-gram. The second, at NIPS 2013 (now NeurIPS), added the techniques that made skip-gram efficient, negative sampling and the subsampling of frequent words, and learned vectors for phrases such as Air Canada. The code and pre-trained vectors were released openly. The best-known set, trained on part of the Google News dataset (about 100 billion words), holds 300-dimensional vectors for 3 million words and phrases.

Word2vec embeddings are static: the method learns one fixed vector for each word in the vocabulary, whatever context it later appears in.

Prediction instead of counting

Instead of counting how often each word w occurs near, say, apricot, word2vec trains a classifier on a binary task: is word w likely to show up near apricot? We do not actually care about this task. We keep the classifier's learned weights, and those weights are the embeddings.

The crucial insight is that running text supplies the answers for free. Any word that really occurs near apricot is a correct "yes", so no human labeling is needed. Learning from labels that come from the data itself is called self-supervision. Word2vec also simplifies earlier neural language models in two ways: it turns predicting a word into binary classification, and it swaps a multi-layer network for what is essentially logistic regression.

Skip-gram with negative sampling (SGNS), the best-known variant, works in four steps:

  1. Step 01: Collect positive examples

    Treat the target word and each neighboring context word as a positive example.

  2. Step 02: Sample negative examples

    Randomly sample other words from the vocabulary and pair them with the target as negative examples.

  3. Step 03: Train a classifier

    Use logistic regression to learn to tell the positive pairs from the negative ones.

  4. Step 04: Keep the weights

    Use the learned weights as the embeddings.

Training examples

Suppose the target word is apricot and the window holds two context words on each side:

Figure 6. Training data for skip-gram with negative sampling, from one position in a sentence: a window of ±2 words around the target w gives four positive pairs, and k = 2 sampled noise words per positive give eight negatives.

Every target-context pair inside the window, such as (apricot, jam), is a positive example. For each positive example the algorithm also draws k noise words, two in the figure, and pairs them with the target as negative examples, such as (apricot, gravel).

The classifier

Given a target w and a candidate context word c, the classifier should return the probability that c is a real context word: high for (apricot, jam), low for (apricot, gravel). It relies on the same intuition as cosine similarity, that similar vectors have a high dot product. A dot product can be any real number, so the sigmoid function σ turns it into a probability:

P(+∣w,c)=σ(𝐜⋅𝐰)=11+exp⁡(−𝐜⋅𝐰)
P(−∣w,c)=1−P(+∣w,c)=σ(−𝐜⋅𝐰)=11+exp⁡(𝐜⋅𝐰)

For a window of L context words, skip-gram simplifies by assuming the context words are independent of each other, so their probabilities multiply, and their logarithms add:

P(+∣w,c1:L)=∏i=1Lσ(𝐜i⋅𝐰)log⁡P(+∣w,c1:L)=∑i=1Llog⁡σ(𝐜i⋅𝐰)

Notice that every word plays two roles, target and context, and skip-gram learns a separate vector for each: a target matrix W and a context matrix C, each with one d-dimensional row per vocabulary word.

The loss and its gradients

For one positive pair (w,cpos) and its k noise words cneg1,…,cnegk, training should push σ(𝐜pos⋅𝐰) towards 1 and every σ(𝐜negi⋅𝐰) towards 0. As a loss to minimize:

L=−[log⁡σ(𝐜pos⋅𝐰)+∑i=1klog⁡σ(−𝐜negi⋅𝐰)]

Its derivatives with respect to the three kinds of vector are short:

∂L∂𝐜pos=[σ(𝐜pos⋅𝐰)−1]𝐰∂L∂𝐜negi=σ(𝐜negi⋅𝐰) 𝐰∂L∂𝐰=[σ(𝐜pos⋅𝐰)−1]𝐜pos+∑i=1kσ(𝐜negi⋅𝐰) 𝐜negi

Stochastic gradient descent moves each vector a small step η against its gradient; for example, 𝐜pos←𝐜pos−η[σ(𝐜pos⋅𝐰)−1]𝐰. Read geometrically, each update moves the target vector towards its real context and away from the noise words, and moves them in turn. Repeated over billions of pairs, words that share contexts end up with similar vectors.

One training step of skip-gram with negative samplingpython
import numpy as np
 
def sigmoid(x):
    return 1 / (1 + np.exp(-x))
 
def sgns_step(w, c_pos, c_neg, lr=0.025):
    """One SGD step for a target vector w, its real context c_pos and k noise
    vectors c_neg (shape k x d). Updates the vectors in place; returns the loss."""
    pos = sigmoid(c_pos @ w)           # P(+ | w, c_pos)
    neg = sigmoid(c_neg @ w)           # P(+ | w, c_neg_i) for each noise word
    loss = float(-np.log(pos) - np.log(1 - neg).sum())
    grad_w = (pos - 1) * c_pos + neg @ c_neg
    c_pos -= lr * (pos - 1) * w        # pull the real context towards w
    c_neg -= lr * neg[:, None] * w     # push the noise words away from w
    w -= lr * grad_w                   # move w towards c_pos, away from the noise
    return loss
 
rng = np.random.default_rng(0)
d, k = 50, 5
w, c_pos, c_neg = rng.normal(0, 0.1, d), rng.normal(0, 0.1, d), rng.normal(0, 0.1, (k, d))
print([round(sgns_step(w, c_pos, c_neg, lr=1.0), 3) for _ in range(5)])
# [4.197, 2.795, 0.815, 0.214, 0.119]

The large learning rate makes the loss fall visibly in five steps; real training uses a small one over many pairs. Since 1−σ(x)=σ(−x), the code's np.log(1 - neg) is the log⁡σ(−𝐜negi⋅𝐰) term of the loss.

When training finishes, each word i has two vectors, 𝐰i and 𝐜i. A common choice is to keep only W; another is to add the two, 𝐰i+𝐜i, which is exactly what GloVe does.

The details that make it work

  • Number of noise words. Mikolov and colleagues found values of k from 5 to 20 useful for small training sets, while for large ones k can be as small as 2 to 5.
  • Which noise words. Noise words are drawn neither uniformly nor by raw frequency, but from the unigram distribution raised to the power 3/4: Pα(w)=count(w)0.75/∑w′count(w′)0.75. The power gives rare words a better chance: if word a has probability 0.99 and word b has 0.01, the weighted probabilities become 0.97 and 0.03. This is the α=0.75 that was later carried over to PPMI.
  • Subsampling frequent words. Words like the occur so often that most of their training pairs teach little. Each occurrence of a word w is discarded with probability 1−t/f(w), where f(w) is the word's frequency and t a threshold, typically around 10−5.
  • Window size. Anything from 1 to 10 words on each side is typical, and the choice changes what kind of similarity the vectors capture, as a later section shows.

CBOW, continuous bag-of-words, turns the prediction around. Instead of using the target word to predict each context word, it uses the context words together (four on each side in the original paper) to predict the word in the middle.

Word2vec in code

The gensim library implements both architectures. Note that it trains CBOW unless you pass sg=1.

Train word2vec with gensim, then query pre-trained vectorspython
from gensim.models import Word2Vec
 
# sentences: an iterable of token lists, such as [["the", "cat", "sat"], ...]
model = Word2Vec(
    sentences,
    vector_size=100,   # embedding dimensions d
    window=5,          # up to 5 context words on each side
    sg=1,              # 1 = skip-gram; the default 0 = CBOW
    negative=5,        # k noise words per positive pair
    ns_exponent=0.75,  # the unigram^0.75 noise distribution
    sample=1e-3,       # subsampling threshold for frequent words
    min_count=5,       # ignore words rarer than this
    epochs=5,
)
vector = model.wv["cat"]                    # a 100-dimensional NumPy array
neighbors = model.wv.most_similar("cat")   # nearest words by cosine
 
# Pre-trained vectors and the classic analogy
import gensim.downloader as api
 
glove = api.load("glove-wiki-gigaword-100")
key, similarity = glove.most_similar(positive=["woman", "king"], negative=["man"])[0]
print(f"{key}: {similarity:.4f}")  # queen: 0.7699 (the gensim documentation's result)

GloVe and fastText

GloVe: global co-occurrence statistics

Word2vec learns from one window at a time and never looks at corpus-wide counts directly. GloVe (Global Vectors; Pennington, Socher and Manning, 2014) starts from the whole word-word co-occurrence matrix. Its key observation is that ratios of co-occurrence probabilities say more than the probabilities themselves. From a 6-billion-token corpus:

k = solidk = gask = waterk = fashion
P(k∣ice)1.9×10−46.6×10−53.0×10−31.7×10−5
P(k∣steam)2.2×10−57.8×10−42.2×10−31.8×10−5
ratio8.98.5×10−21.360.96

Solid is related to ice but not to steam, so its ratio is large; gas is the reverse, so its ratio is small; water relates to both and fashion to neither, so their ratios sit close to 1. The ratio cancels out the noise and keeps what distinguishes the two words. GloVe therefore fits vectors whose dot product, plus two bias terms, approximates the logarithm of the co-occurrence count, with a weighted least-squares objective:

J=∑i,j=1Vf(Xij)(𝐰i⊤𝐰~j+bi+b~j−log⁡Xij)2f(x)={(x/xmax⁡)αif x<xmax⁡1otherwise

Xij is how often word j occurs in the context of word i; 𝐰 and 𝐰~ are word and context vectors; b and b~ are biases. The weighting f ignores pairs that never co-occur, where the logarithm is undefined, down-weights rare pairs and caps frequent ones. The paper uses xmax⁡=100 and α=3/4, and takes W+W~ as the final word vectors.

The two families turned out to be closer than they look. Levy and Goldberg (2014) showed that skip-gram with negative sampling implicitly factorizes a word-context matrix of PMI values shifted by a constant: at its optimum, 𝐰⋅𝐜=PMI(w,c)−log⁡k. Counting and predicting are two routes to similar geometry, and Levy, Goldberg and Dagan (2015) found that much of word2vec's advantage came from design choices, such as the smoothing above, that transfer to count-based methods.

fastText: vectors for pieces of words

Word2vec and GloVe have no vector for a word they did not see in training, and they treat walk, walks and walking as unrelated symbols. fastText (Bojanowski, Grave, Joulin and Mikolov, 2017) represents each word as a bag of character n-grams from 3 to 6 characters long, plus the word itself, with boundary symbols marking its start and end. With n=3, where becomes <wh, whe, her, ere and re>, plus the special sequence <where>; the word her, written <her>, stays distinct from the trigram her inside where.

Each n-gram has its own vector, and a word's vector is the sum of its n-gram vectors. Two things follow. Words that share pieces, such as walking and walked, share part of their representation. And the model can build a sensible vector for a word it never saw, such as a rare inflection or a misspelling, from the n-grams it does know.

Semantic properties of embeddings

Window size changes what "similar" means

The context window shapes sparse and dense vectors alike, and it changes the kind of similarity they capture. Short windows give more syntactic representations: a word's nearest neighbors tend to be semantically similar words with the same part of speech. Long windows give more topical ones: the nearest neighbors are related to the word without necessarily being similar to it. Levy and Goldberg (2014) show this with the five nearest neighbors of hogwarts in skip-gram embeddings trained on English Wikipedia:

WindowNearest neighbors of hogwarts
2 words on each sideevernight, sunnydale, garderobe, blandings, collinwood
5 words on each sidedumbledore, hallows, half-blood, malfoy, snape

With the narrow window, hogwarts sits among other fictional schools and places; with the wider one, among the people and things of the Harry Potter books.

Analogies and the parallelogram model

Embeddings capture relations between words, too. The parallelogram model of Rumelhart and Abrahamson (1973) solves analogy problems of the form a:b::a∗:b∗. For apple is to tree as grape is to what?, it takes the vector from apple to tree, adds it to grape, and returns the word nearest the result, ideally vine. Mikolov and colleagues found that word2vec embeddings support the same arithmetic: the vector for king, minus the vector for man, plus the vector for woman, lands closest to the vector for queen.

Figure 7. The parallelogram model of analogy: the offset from man to woman, added to king, lands near queen. A schematic, not real coordinates.
b^∗=argmin⁡x  distance(𝐱,  𝐛−𝐚+𝐚∗)

With cosine as the measure, that means returning the word whose vector has the highest cosine with 𝐛−𝐚+𝐚∗. The method needs care in practice:

  • The nearest vector to 𝐛−𝐚+𝐚∗ is very often one of the input words or a variant of one, so implementations exclude a, b and a∗ from the candidates.
  • Linzen (2016) showed that the method's reliance on cosine similarity mixes two things together: whether the offsets between word pairs are really consistent, and how words happen to cluster in the space. Analogy scores can look better than the underlying relations are.
  • It works best for frequent words, short distances and a few specific relations, such as countries and their capitals or verbs and their inflected forms.

Embeddings inherit bias

Embeddings learn whatever regularities their training text contains, including social stereotypes. Bolukbasi and colleagues (NIPS 2016) showed that "even word embeddings trained on Google News articles exhibit female/male gender stereotypes to a disturbing extent"; their paper takes its title from an analogy the embeddings produced, man is to computer programmer as woman is to homemaker, and showed that gender is captured by a direction in the embedding space. Caliskan, Bryson and Narayanan (2017) introduced the Word Embedding Association Test (WEAT) and used it to replicate a spectrum of human biases measured by the Implicit Association Test. Anything built on embeddings, search ranking and RAG retrieval included, can carry these biases into its results.

Evaluating embeddings

Intrinsic evaluation tests the vectors directly. The most common method compares a model's similarity scores for word pairs with human ratings, using Spearman rank correlation.

  • WordSim-353 (Finkelstein and colleagues): 353 word pairs, each rated from 0 (totally unrelated) to 10 (very much related or identical). Plane and car average 5.77, cup and coffee 6.58, journey and voyage 9.29.
  • SimLex-999 (Hill, Reichart and Korhonen, 2015): explicitly quantifies similarity rather than relatedness, so pairs that are associated but not similar, such as Freud and psychology, receive low ratings. It covers concrete and abstract adjective, noun and verb pairs. Its authors point out that WordSim-353 rates coffee and cup as more "similar" than car and train, which share many properties.
  • Analogy sets. Mikolov and colleagues' semantic-syntactic test set has 8,869 semantic and 10,675 syntactic questions, such as Athens : Greece :: Oslo : ?.

Extrinsic evaluation measures how much the vectors help a real task: classification, clustering, retrieval or reranking. For modern text embeddings the reference point is MTEB, the Massive Text Embedding Benchmark (Muennighoff and colleagues), which spans 8 task types, 58 datasets and 112 languages. Benchmarking 33 models, its authors found that "no particular text embedding method dominates across all tasks". The practical lesson: look at the results for the task you actually have, then test on your own data.

Contextual embeddings: one vector per occurrence

Every embedding so far is static: one vector per word type. That runs straight into the polysemy problem from the start of the article. Bank gets a single vector, a blend of its financial and river senses, whichever one a sentence uses.

Contextual embeddings fix this by computing a fresh vector for every occurrence of a word, from the whole sentence around it. ELMo (Peters and colleagues, NAACL 2018) used a bidirectional language model whose representations model how the uses of a word "vary across linguistic contexts (i.e., to model polysemy)". BERT (Devlin and colleagues, 2019) pre-trained a transformer to build representations "by jointly conditioning on both left and right context in all layers". Its base model has 12 layers and 768-dimensional vectors, and it splits text into subword tokens from a WordPiece vocabulary of 30,000, so, as with fastText, rare and unseen words are broken into known pieces rather than lost.

Search and RAG need one vector per sentence, passage or document, not one per token. Two designs compete.

A cross-encoder feeds the query and a passage into the model together and outputs a relevance score. It is accurate, but every query-passage pair needs its own pass through the model, which does not scale: Reimers and Gurevych (2019) note that finding the most similar pair among 10,000 sentences with BERT this way takes about 50 million inference computations, roughly 65 hours.

A bi-encoder encodes each text on its own into one vector, so passages are embedded once, ahead of time, and stored in a vector index; a query then costs one encoding and a nearest-neighbor search. Reimers and Gurevych's Sentence-BERT fine-tuned BERT in a siamese network to produce such vectors, cutting that same search "from 65 hours with BERT / RoBERTa to about 5 seconds", while keeping BERT's accuracy. Dense Passage Retrieval (Karpukhin and colleagues, 2020) trained a bi-encoder for open-domain question answering and outperformed a strong Lucene-BM25 system by 9 to 19 percentage points in top-20 passage retrieval accuracy. Embedding APIs and models used in RAG, such as OpenAI's embeddings or Sentence Transformers, follow this bi-encoder design. Many systems combine the two: a bi-encoder or BM25 retrieves a few hundred candidates quickly, and a cross-encoder reranks the top of the list.

Two designs sit between sparse and dense:

  • Late interaction. ColBERT (Khattab and Zaharia, 2020) encodes the query and the document independently, keeps one vector per token, and scores them with a cheap interaction step that compares the token vectors. It is competitive with BERT-based rankers while running two orders of magnitude faster.
  • Learned sparse retrieval. SPLADE (Formal, Piwowarski and Clinchant, 2021) uses a transformer to produce sparse vectors over the vocabulary, with explicit sparsity regularization and a log-saturation of term weights, and can expand a text with related terms it does not contain. The result keeps exact term matching and can be served from an inverted index, like BM25.

How many dimensions?

Embedding size trades quality against the cost of storing and searching millions of vectors. Matryoshka Representation Learning (Kusupati and colleagues, NeurIPS 2022) trains embeddings coarse to fine, so that the leading dimensions carry the most information and a prefix of the vector can stand in for the whole, like nested dolls; the authors report up to 14 times smaller embeddings for ImageNet-1K classification at the same accuracy. OpenAI's text-embedding-3 models offer the same kind of shortening through a dimensions parameter. By default text-embedding-3-small returns 1,536 dimensions and text-embedding-3-large 3,072, and OpenAI reports that text-embedding-3-large shortened to 256 dimensions still outperforms the full 1,536-dimensional text-embedding-ada-002 on MTEB. If you truncate a normalized vector yourself, normalize it again afterwards: the shorter vector has a length below 1, so its dot products are no longer cosines.

Sentence embeddings with Sentence Transformerspython
from sentence_transformers import SentenceTransformer
 
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
 
sentences = [
    "That is a happy person",
    "That is a happy dog",
    "That is a very happy person",
    "Today is a sunny day",
]
embeddings = model.encode(sentences)                     # shape (4, 384)
similarities = model.similarity(embeddings, embeddings)  # cosine by default, shape (4, 4)

The all-MiniLM-L6-v2 model maps each sentence to a 384-dimensional vector and truncates input longer than 256 word pieces, so long documents are split into chunks before embedding, as in the RAG indexing step.

Try it: a vector search playground

Everything so far comes together in what a retriever does with each query. In the playground below, ten short documents, or the 33 words they contain, are the vector store. Pick a query, a sparse representation (TF-IDF or BM25) or a dense one (GloVe), and a way to measure closeness, then step through the search: index the store, embed the query, measure every distance and retrieve the top three. Every number is computed live with the formulas above.

Some things to try:

  • Query bank with TF-IDF. The two finance documents and the river document all match, and the river one ties for first, because a sparse vector only sees the string bank. Add money and nothing changes, since money appears in no document. Switch to GloVe and the finance documents move ahead.
  • Query kitten with TF-IDF and there is no query vector at all: the vocabulary mismatch problem. With GloVe, the cat document comes first.
  • Keep kitten and GloVe, and compare the measures. The dot product puts the puppy document just ahead of the cat document, because longer vectors score higher; cosine and Euclidean distance put the cat document first. Tick "Normalize vectors to length 1" and all three agree.
  • Switch the store to words and query cat. TF-IDF calls mat and sleeps identical to cat, because the three share one document; GloVe, trained on billions of words, returns cats, dogs and puppy.

Vector search playground

An interactive 3D view of a small vector store: pick a query, a representation and a distance measure, and step through the search. It loads as you scroll here, and needs JavaScript.

The dense vectors are real GloVe vectors: 50 dimensions, trained on 6 billion tokens of Wikipedia and newswire text. A document's vector is the average of its words' vectors, the simplest kind of sentence embedding. Production retrievers use models trained for the job, such as the bi-encoders above, but every search runs through the same four steps.

Sparse or dense: choosing for retrieval

MethodRepresentationStrengthsWeaknesses
TF-IDFSparse, one weight per vocabulary termSimple, fast and interpretableNo synonyms; linear term frequency; no direct length control
BM25Sparse, with saturated term frequency and length normalizationStrong zero-shot baseline; exact matches on names and codes; inverted indexMisses paraphrases that use different words
Dense bi-encoderOne dense vector per textMatches meaning and paraphraseCan miss rare exact terms; often weaker outside its training domain; needs a vector index
Learned sparse (SPLADE)Sparse, learned term weights with expansionInverted index with some semantic matchingNeeds a trained model at index and query time
Late interaction (ColBERT)One vector per tokenClose to cross-encoder qualityStores many vectors per document
Cross-encoderNo stored vectors; scores query-passage pairsThe most accurateToo slow to search a collection; used for reranking

Hybrid search, BM25 and a dense retriever merged with reciprocal rank fusion, is a common default for RAG precisely because the two tend to fail on different queries.

Formula sheet

ConceptFormulaRemember
Dot product𝐯⋅𝐰=∑iviwiFavors long, frequent vectors
Cosine𝐯⋅𝐰∥𝐯∥ ∥𝐰∥Angle only; 0 to 1 for counts
Unit vectors∥𝐚−𝐛∥2=2−2cos⁡(𝐚,𝐛)Distance and cosine rank alike
Term frequency1+log⁡10count(t,d), or 01, 10 and 100 occurrences give 1, 2 and 3
IDFlog⁡10(N/dft)0 for a word in every document
TF-IDFtft,d×idftFor term-document matrices
BM25 termIDF⋅f (k1+1)f+k1(1−b+b⋅dl/avgdl)Saturates at k1+1; defaults k1=1.2, b=0.75
BM25 IDF (Lucene)ln⁡(1+N−n+0.5n+0.5)Never negative
PMIlog⁡2P(w,c)P(w) P(c)Observed over expected co-occurrence
PPMImax⁡(PMI,0)Smooth context counts with α=0.75
Skip-gramP(+∣w,c)=σ(𝐜⋅𝐰)A sigmoid of a dot product
SGNS loss−log⁡σ(𝐜pos⋅𝐰)−∑ilog⁡σ(−𝐜negi⋅𝐰)k = 5 to 20 noise words for small data, 2 to 5 for large
Noise distributioncount(w)0.75/∑w′count(w′)0.75Lifts rare words
Analogyargmax⁡xcos⁡(𝐱,𝐛−𝐚+𝐚∗)Exclude the input words

Test yourself

Why does cosine similarity divide by the vectors' lengths?

The raw dot product grows with vector length, and frequent words have long vectors, so it would rate common words as similar to everything. Dividing by both lengths leaves only the angle between the vectors, which does not depend on frequency.

A word appears in every document of a collection. What is its IDF, and what does that do to its TF-IDF weight?

log⁡10(N/N)=0, so its TF-IDF weight is 0 in every document, however often it occurs.

Which two weaknesses of TF-IDF does BM25 address, and which parameter controls each?

Term frequency that keeps growing, which BM25 saturates under the control of k1; and the advantage of long documents, which BM25 removes with length normalization controlled by b.

What happens to BM25 with k1 = 0? And with b = 0?

With k1=0 the term-frequency part equals 1 for any non-zero count, so only the presence of a term matters, and document length no longer has any effect because it only ever multiplies k1. With b=0, length normalization is switched off but saturation remains.

Why can the classic BM25 IDF be negative, and how does Lucene avoid it?

For a term in more than half the documents, (N−n+0.5)/(n+0.5) is below 1, so its logarithm is negative. Lucene adds 1 inside the logarithm.

What does a PMI of 0 mean, and why use PPMI instead of PMI?

A PMI of 0 means the two words co-occur exactly as often as chance predicts. Negative values, claiming that words avoid each other, cannot be estimated reliably without enormous corpora, so PPMI replaces them with 0.

Where do the labels come from when training skip-gram with negative sampling?

From the text itself. Words inside the window around the target are positive examples, and words sampled from the noise distribution are negative examples. No human labeling is needed, which is why the method is called self-supervised.

Why are noise words sampled from the unigram distribution raised to the power 0.75?

It flattens the distribution, so rare words are sampled more often than their raw frequency alone would give, while frequent words still dominate. Probabilities of 0.99 and 0.01 become 0.97 and 0.03.

How does fastText produce a vector for a word it never saw in training?

It adds up the vectors of the word's character n-grams, from 3 to 6 characters long with boundary symbols, which it learned from other words that contain them.

What is the difference between a static and a contextual embedding of the word bank?

A static embedding gives bank one vector for all of its senses. A contextual model such as BERT computes a different vector for each occurrence from the sentence around it, so the financial and river senses get different vectors.

For first-stage retrieval over millions of passages, would you use a bi-encoder or a cross-encoder, and why?

A bi-encoder. Passages are embedded once, ahead of time, and a query needs one encoding and a nearest-neighbor search. A cross-encoder needs a full model pass for every query-passage pair, so it is used to rerank a short candidate list instead.

Your embeddings are normalized to length 1. Does it matter whether the vector database uses cosine, dot product or Euclidean distance?

Not for the ranking. For unit vectors the dot product equals the cosine, and the squared Euclidean distance is 2−2cos⁡, so all three order the neighbors the same way.

Further reading

Keep reading