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.
| Word | Valence | Arousal | Dominance |
|---|---|---|---|
| courageous | 8.05 | 5.50 | 7.38 |
| music | 7.67 | 5.57 | 6.50 |
| heartbreak | 2.45 | 5.65 | 3.58 |
| cub | 6.71 | 3.95 | 4.24 |
| innocent | 6.55 | 4.40 | 5.92 |
| naive | 4.22 | 3.86 | 5.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.
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:
| Word | As You Like It | Twelfth Night | Julius Caesar | Henry V |
|---|---|---|---|---|
| battle | 1 | 0 | 7 | 13 |
| good | 114 | 80 | 62 | 89 |
| fool | 36 | 58 | 1 | 4 |
| wit | 20 | 15 | 2 | 3 |
Read down a column and you get a document vector: As You Like It is and Henry V is . 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, 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. 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:
Retrieval works the same way. Represent the query as a vector over the same 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 and fool is . 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 , 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:
| Target | aardvark | computer | data | result | pie | sugar |
|---|---|---|---|---|---|---|
| cherry | 0 | 2 | 8 | 9 | 442 | 25 |
| strawberry | 0 | 0 | 0 | 1 | 60 | 19 |
| digital | 0 | 1,670 | 1,683 | 85 | 5 | 4 |
| information | 0 | 3,325 | 3,982 | 378 | 5 | 13 |
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:
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 , the natural starting point is the dot product:
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
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:
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, .
The cosine runs from 1 for vectors pointing the same way, through 0 for vectors at right angles, to 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:
| Word | pie | data | computer |
|---|---|---|---|
| cherry | 442 | 8 | 2 |
| digital | 5 | 1,683 | 1,670 |
| information | 5 | 3,982 | 3,325 |
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.
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.996Cosine, 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 , 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 in document starts as a plain count, . 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:
One occurrence gives a weight of 1, ten give 2 and a hundred give 3. A common alternative is .
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 of a term is the number of documents it occurs in, not the total number of times it occurs. The inverse document frequency is
where 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 . The logarithm compresses the range again, since 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:
| Word | df | idf |
|---|---|---|
| Romeo | 1 | 1.568 |
| salad | 2 | 1.267 |
| Falstaff | 4 | 0.966 |
| forest | 12 | 0.489 |
| battle | 21 | 0.246 |
| wit | 34 | 0.037 |
| fool | 36 | 0.012 |
| good | 37 | 0 |
| sweet | 37 | 0 |
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:
Applied to the four-play matrix, using each word's idf from the full collection of 37 plays:
| Word | As You Like It | Twelfth Night | Julius Caesar | Henry V |
|---|---|---|---|---|
| battle | 0.246 | 0 | 0.454 | 0.520 |
| good | 0 | 0 | 0 | 0 |
| fool | 0.030 | 0.033 | 0.012 | 0.019 |
| wit | 0.085 | 0.080 | 0.048 | 0.054 |
To check one cell: battle occurs 13 times in Henry V, so ; it appears in 21 of the 37 plays, so ; and . 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:
The ones in the fraction act as if one extra document contained every term once, which prevents division by zero, and the final keeps a term that occurs in every document from being ignored entirely.
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 and .
The formula
For a query with terms and a document , BM25 adds up one contribution per query term:
- is the term's frequency in the document: how many times it occurs there.
- is the document's length in words, and the average document length in the collection.
- controls how quickly term frequency saturates.
- , between 0 and 1, controls how strongly scores are normalized for document length.
- 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 . As grows this rises quickly, then flattens out towards an upper limit of . However often a term repeats, its contribution is capped.
With the default , one occurrence scores 1.0, two score 1.375, five score 1.774 and twenty score 2.075, against a ceiling of 2.2. sets the bend. At the term-frequency part equals 1 for any count, so the formula only asks whether the term is present. As 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 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 :
It multiplies in the denominator. A document twice the average length has with , 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 normalization is full; with 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
where is the number of documents and 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:
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 documents with an average length of 100 words, the defaults and , and the query jaguar speed. Jaguar is rare, appearing in 10 documents; speed is common, appearing in 300:
Four documents, with their lengths and term counts:
| Document | Length | jaguar | speed | Score |
|---|---|---|---|---|
| D1 | 100 | 1 | 1 | 5.761 |
| D2 | 100 | 4 | 0 | 7.712 |
| D3 | 400 | 4 | 0 | 5.077 |
| D4 | 100 | 0 | 6 | 2.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: . With a linear term frequency it would have been .
- Length. D3 has the same four mentions as D2 but is four times as long, so , and its score falls from 7.712 to .
- Rarity. D4 mentions speed six times and still ranks last: six mentions of a common term are worth , less than a single mention of the rare one.
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 , 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 and 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:
The numerator is how often target and context 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 by hand
The probabilities are estimated from counts. Here is the word-word table again, with each row's and each column's total:
| Word | computer | data | result | pie | sugar | count(w) |
|---|---|---|---|---|---|---|
| cherry | 2 | 8 | 9 | 442 | 25 | 486 |
| strawberry | 0 | 0 | 1 | 60 | 19 | 80 |
| digital | 1,670 | 1,683 | 85 | 5 | 4 | 3,447 |
| information | 3,325 | 3,982 | 378 | 5 | 13 | 7,703 |
| count(c) | 4,997 | 5,673 | 473 | 512 | 61 | 11,716 |
With the count of word with context , every probability is a count divided by the grand total:
For information with the context data:
The whole PPMI matrix:
| Word | computer | data | result | pie | sugar |
|---|---|---|---|---|---|
| cherry | 0 | 0 | 0 | 4.38 | 3.30 |
| strawberry | 0 | 0 | 0 | 4.10 | 5.51 |
| digital | 0.18 | 0.01 | 0 | 0 | 0 |
| information | 0.02 | 0.09 | 0.28 | 0 | 0 |
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 before turning them into probabilities, which gives rare contexts a higher probability than their counts alone, and so a lower PMI:
Levy, Goldberg and Dagan (2015) found that 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 to every count before computing PMI, which discounts all the non-zero values, and discounts them more the larger is.
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 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 occurs near, say, apricot, word2vec trains a classifier on a binary task: is word 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:
Step 01: Collect positive examples
Treat the target word and each neighboring context word as a positive example.
Step 02: Sample negative examples
Randomly sample other words from the vocabulary and pair them with the target as negative examples.
Step 03: Train a classifier
Use logistic regression to learn to tell the positive pairs from the negative ones.
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:
Every target-context pair inside the window, such as (apricot, jam), is a positive example. For each positive example the algorithm also draws noise words, two in the figure, and pairs them with the target as negative examples, such as (apricot, gravel).
The classifier
Given a target and a candidate context word , the classifier should return the probability that 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:
For a window of context words, skip-gram simplifies by assuming the context words are independent of each other, so their probabilities multiply, and their logarithms add:
Notice that every word plays two roles, target and context, and skip-gram learns a separate vector for each: a target matrix and a context matrix , each with one -dimensional row per vocabulary word.
The loss and its gradients
For one positive pair and its noise words , training should push towards 1 and every towards 0. As a loss to minimize:
Its derivatives with respect to the three kinds of vector are short:
Stochastic gradient descent moves each vector a small step against its gradient; for example, . 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.
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 , the code's np.log(1 - neg) is the term of the loss.
When training finishes, each word has two vectors, and . A common choice is to keep only ; another is to add the two, , which is exactly what GloVe does.
The details that make it work
- Number of noise words. Mikolov and colleagues found values of from 5 to 20 useful for small training sets, while for large ones 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 : . The power gives rare words a better chance: if word has probability 0.99 and word has 0.01, the weighted probabilities become 0.97 and 0.03. This is the 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 is discarded with probability , where is the word's frequency and a threshold, typically around .
- 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.
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:
| = solid | = gas | = water | = fashion | |
|---|---|---|---|---|
| ratio | 8.9 | 1.36 | 0.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:
is how often word occurs in the context of word ; and are word and context vectors; and are biases. The weighting ignores pairs that never co-occur, where the logarithm is undefined, down-weights rare pairs and caps frequent ones. The paper uses and , and takes 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, . 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 , 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:
| Window | Nearest neighbors of hogwarts |
|---|---|
| 2 words on each side | evernight, sunnydale, garderobe, blandings, collinwood |
| 5 words on each side | dumbledore, 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 . 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.
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 , and 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.
Sentence embeddings for search
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.
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
| Method | Representation | Strengths | Weaknesses |
|---|---|---|---|
| TF-IDF | Sparse, one weight per vocabulary term | Simple, fast and interpretable | No synonyms; linear term frequency; no direct length control |
| BM25 | Sparse, with saturated term frequency and length normalization | Strong zero-shot baseline; exact matches on names and codes; inverted index | Misses paraphrases that use different words |
| Dense bi-encoder | One dense vector per text | Matches meaning and paraphrase | Can miss rare exact terms; often weaker outside its training domain; needs a vector index |
| Learned sparse (SPLADE) | Sparse, learned term weights with expansion | Inverted index with some semantic matching | Needs a trained model at index and query time |
| Late interaction (ColBERT) | One vector per token | Close to cross-encoder quality | Stores many vectors per document |
| Cross-encoder | No stored vectors; scores query-passage pairs | The most accurate | Too 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
| Concept | Formula | Remember |
|---|---|---|
| Dot product | Favors long, frequent vectors | |
| Cosine | Angle only; 0 to 1 for counts | |
| Unit vectors | Distance and cosine rank alike | |
| Term frequency | , or 0 | 1, 10 and 100 occurrences give 1, 2 and 3 |
| IDF | 0 for a word in every document | |
| TF-IDF | For term-document matrices | |
| BM25 term | Saturates at ; defaults , | |
| BM25 IDF (Lucene) | Never negative | |
| PMI | Observed over expected co-occurrence | |
| PPMI | Smooth context counts with | |
| Skip-gram | A sigmoid of a dot product | |
| SGNS loss | = 5 to 20 noise words for small data, 2 to 5 for large | |
| Noise distribution | Lifts rare words | |
| Analogy | 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?
, 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 ; and the advantage of long documents, which BM25 removes with length normalization controlled by .
What happens to BM25 with k1 = 0? And with b = 0?
With 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 . With , 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, 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 , so all three order the neighbors the same way.
Further reading
- Daniel Jurafsky and James H. Martin, Speech and Language Processing, the chapter on vector semantics and embeddings: the textbook treatment this article's first half follows.
- Stephen Robertson and Hugo Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond, Foundations and Trends in Information Retrieval, 2009.
- Karen Spärck Jones, A Statistical Interpretation of Term Specificity and its Application in Retrieval, Journal of Documentation, 1972.
- Kenneth Church and Patrick Hanks, Word Association Norms, Mutual Information, and Lexicography, Computational Linguistics, 1990.
- Tomas Mikolov and colleagues, Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality, 2013.
- Jeffrey Pennington, Richard Socher and Christopher Manning, GloVe: Global Vectors for Word Representation, EMNLP 2014.
- Piotr Bojanowski and colleagues, Enriching Word Vectors with Subword Information, TACL 2017.
- Omer Levy and Yoav Goldberg, Neural Word Embedding as Implicit Matrix Factorization, NIPS 2014, and Dependency-Based Word Embeddings, ACL 2014.
- Omer Levy, Yoav Goldberg and Ido Dagan, Improving Distributional Similarity with Lessons Learned from Word Embeddings, TACL 2015.
- Nils Reimers and Iryna Gurevych, Sentence-BERT, EMNLP 2019, and Vladimir Karpukhin and colleagues, Dense Passage Retrieval for Open-Domain Question Answering, EMNLP 2020.
- Nandan Thakur and colleagues, BEIR, 2021, and Niklas Muennighoff and colleagues, MTEB: the benchmarks for retrieval and for text embeddings.
- RAG Explained: how these vectors are used to index, retrieve and generate.