Embeddings & Vector Arithmetic

Agentic AI · L-Embed

Text as a vector: the geometry that turns "similar in meaning" into "close in $\mathbb{R}^d$", how that geometry is trained rather than found, and the nearest-neighbour search an agent runs over it.

Prerequisite: the recap Linear Algebra.

Learning Objectives

After this week you can:

  1. Compute cosine similarity and Euclidean distance, and state when the two rank neighbours identically.
  2. Explain what an embedding is and why semantic similarity ≈ geometric closeness.
  3. Distinguish a vector per word type, per word token and per text, and say which problem each granularity solves.
  4. Describe how a word vector is trained from co-occurrence — CBOW, skip-gram and the co-occurrence-ratio argument of GloVe.
  5. Explain why a text vector must be trained rather than pooled from an untuned contextual model, and read the InfoNCE objective that trains it.
  6. Perform semantic search by nearest neighbour over embeddings, and explain why a bi-encoder makes that search possible where a cross-encoder does not.
  7. Distinguish symmetric from asymmetric embedding tasks and apply the matching task prefixes.
  8. Say where agents use embeddings — retrieval (RAG), memory, tool selection.

Overview

An agent compares text by meaning rather than by exact words: to retrieve a relevant document, to recall a stored fact, or to select one tool out of many. The construction that makes such a comparison computable is the embedding — a map from text to a vector in which closeness is similarity.

Vectors, the dot product, norms and the angle between two vectors are recapped in Linear Algebra; Part I adds the two measures by which embeddings are compared, Part II states how one vector per word type is learned from co-occurrence, Part III how a vector is computed for a word token and for a whole text, and Part IV how an agent searches a collection of text vectors:

Part The question it answers Sections
I · Vector Math By which measures are two vectors in $\mathbb{R}^d$ compared, and under which condition do the measures produce the same ranking? Cosine Similarity · Euclidean Distance
II · Sparse Vectors and Word Embeddings What is an embedding, and how is one vector per word type learned from the co-occurrence statistics of a corpus? Sparse Vectors · Dense Vectors via Embedding · Meaning ≈ Geometry · Word Embeddings and the Distributional Hypothesis · CBOW and Skip-gram · Global Co-occurrence Counts: GloVe
III · Contextual and Text Embeddings How is a vector computed for a word token in its sentence and for a whole text, and why must the vector of a text be trained? From Word Types to Word Tokens · The Bidirectional Transformer Stack: BERT · From Word Vectors to Text Vectors · From Geometry to Systems: Bi-Encoders vs. Cross-Encoders · Contrastive Training · The Text-Embedder Family · Tokenization in an Embedder
IV · Semantic Search How is a collection of text vectors searched for a query, and for which purposes does an agent use that search? Semantic Search as Nearest-Neighbour Search · Symmetric and Asymmetric Tasks · Embeddings in Agents

Part I — Vector Math

Every construction in this lecture reduces to a comparison of two vectors in $\mathbb{R}^d$. Vectors, the dot product, norms and the angle between two vectors are a prerequisite of the lecture, recapped in Linear Algebra; this part adds the two measures by which embeddings are compared.

For an agent this comparison decides which stored text — a document passage, a memory, a tool description — is placed in the context window (see Embeddings in Agents); the two measures differ in whether the length of a vector takes part in that decision.

Cosine Similarity

Cosine similarity uses the cosine of the angle between two vectors (Linear Algebra) as a measure of similarity: it compares the directions of two embeddings and ignores their lengths.

$$ S_C(\mathbf{u},\mathbf{v}) = \frac{\mathbf{u}\cdot\mathbf{v}}{\|\mathbf{u}\|_2\,\|\mathbf{v}\|_2} = \cos\theta \;\in\; [-1, 1] $$

  • $S_C = 1$: the same direction, the most similar pair; $S_C = 0$: orthogonal vectors, an unrelated pair; $S_C = -1$: opposite directions.
  • Scale invariance: multiplying either vector by a positive factor leaves $S_C$ unchanged, so the length of an embedding does not enter the comparison.

Euclidean Distance

The Euclidean distance of two vectors is the length of their difference vector.

$$ \|\mathbf{u}-\mathbf{v}\|_2 = \sqrt{\sum_i (u_i - v_i)^2} $$

Expanding the square gives $$ \|\mathbf{u}-\mathbf{v}\|_2^2 = \|\mathbf{u}\|_2^2 + \|\mathbf{v}\|_2^2 - 2\,\mathbf{u}\cdot\mathbf{v}. $$ For unit vectors this is $2 - 2\cos\theta$ — so on normalized embeddings, Euclidean distance and cosine similarity rank neighbours identically.

In [1]:
import numpy as np

u = np.array([2.0, 1.0, 0.0])
v = np.array([1.0, 1.0, 1.0])

dot = u @ v
cos = dot / (np.linalg.norm(u) * np.linalg.norm(v))
euc = np.linalg.norm(u - v)
print(f"dot={dot:.3f}  cosine={cos:.3f}  euclidean={euc:.3f}")
dot=3.000  cosine=0.775  euclidean=1.414

Part II — Sparse Vectors and Word Embeddings

A word embedding assigns one vector to each word type of a fixed vocabulary; the vector is learned from the co-occurrence statistics of a corpus, so that words which occur in similar contexts receive nearby vectors. The embedding is a dense vector of a few hundred learned real numbers; the alternative is a sparse vector with one dimension per word of the vocabulary, whose entries are word counts weighted by how rare each word is across documents (tf-idf) (Jurafsky & Martin, 2026, §11.1). Retrieval systems divide along the same line: sparse retrieval compares the weighted word counts of a query and a document, dense retrieval their embeddings.

For an agent the two kinds of vector fail differently. A dense vector places texts of similar use near each other whether or not they are true, so a retrieved passage is checked before the agent acts on it; a sparse vector matches exact strings such as error codes and function names, which a dense vector misses (see Semantic Search as Nearest-Neighbour Search).

Sparse Vectors

The bag-of-words vector. The vector space model represents a document $d$ by the counts of the words it contains; the order of the words is discarded and only their frequency is kept, which is why the model is also called the bag-of-words model (Jurafsky & Martin, 2026, §11.1.1). The vector has one entry per word of the vocabulary $V$, so its length is $|V|$, typically 10,000 to 50,000, and almost all of its entries are zero (Jurafsky & Martin, 2026, §5.3). With $\mathbf{e}_w$ the one-hot vector of the word $w$, i.e. a 1 in the dimension of $w$ and 0 in every other, the count vector of a document $d = w_{d,1} \dots w_{d,|d|}$ of $|d|$ tokens — a word that occurs $k$ times occupies $k$ of the $|d|$ positions — is the sum of the one-hot vectors of its tokens:

$$\mathbf{x}_d = \sum_{i=1}^{|d|} \mathbf{e}_{w_{d,i}}, \qquad x_{d,t} = \sum_{i=1}^{|d|} \mathbb{1}[w_{d,i} = t] = \operatorname{count}(t, d),$$

where the indicator $\mathbb{1}[w_{d,i} = t]$ is 1 if the $i$-th token of $d$ is the word $t$ and 0 otherwise. For the cat sees the dog the one-hot vector of the is added twice, and its entry is 2.

The count vectors of a collection, placed side by side as columns, form the term-document matrix: one row per word, one column per document.

Example — length and direction. Two count vectors are compared with the measures of Cosine Similarity and Euclidean Distance. A 5-page document $d_1$ about cats and a one-sentence tweet $d_2$ about cats use the same words in similar proportions, so $\mathbf{x}_{d_1}$ and $\mathbf{x}_{d_2}$ point in nearly the same direction: the angle $\theta$ between them is close to $0^\circ$, and $S_C(\mathbf{x}_{d_1}, \mathbf{x}_{d_2}) = \cos\theta \approx 1$. The length of a count vector grows with the text, so $\|\mathbf{x}_{d_1}\|_2$ is much larger than $\|\mathbf{x}_{d_2}\|_2$, and the Euclidean distance $\|\mathbf{x}_{d_1} - \mathbf{x}_{d_2}\|_2$ is large. The cosine similarity divides the dot product by both norms and therefore compares the directions only.

Weighting: tf-idf

Retrieval does not use the raw counts. It multiplies two weights, each of which corrects one defect of the count (Jurafsky & Martin, 2026, §11.1.2):

  • Term frequency measures how important a word is within one document. A word that occurs more often in a document is likely to be informative about the content of the document, but a word occurring 100 times is not 100 times as informative as a word occurring once. The weight therefore grows with the count, but more slowly than the count.
  • Inverse document frequency measures how well a word distinguishes one document from the others in the collection. A word that occurs in only a few documents separates those documents from the rest; a word that occurs in every document separates none. The weight therefore falls as the number of documents containing the word rises.

The term frequency replaces the count by its logarithm, so the weight rises by 1 for every tenfold increase of the count (counts 1, 10, 100 give weights 1, 2, 3):

$$\mathrm{tf}_{t,d} = \begin{cases} 1 + \log_{10} \operatorname{count}(t,d) & \text{if } \operatorname{count}(t,d) > 0, \\ 0 & \text{otherwise.} \end{cases}$$

The document frequency $\mathrm{df}_t$ of a word $t$ is the number of documents in the collection that contain $t$ at least once. It counts documents, not occurrences: a document in which $t$ occurs 100 times adds 1 to $\mathrm{df}_t$, as does a document in which $t$ occurs once. For a collection of $N$ documents and a word of the vocabulary, $1 \le \mathrm{df}_t \le N$, and

$$\mathrm{idf}_t = \log_{10} \frac{N}{\mathrm{df}_t},$$

so a word that occurs in every document has $\mathrm{idf}_t = \log_{10} 1 = 0$.

The entry of the document vector is $\text{tf-idf}(t,d) = \mathrm{tf}_{t,d} \cdot \mathrm{idf}_t$. In the 37 plays of Shakespeare, Romeo occurs in one play ($\mathrm{idf} = \log_{10} 37 = 1.57$), battle in 21 ($0.246$) and good in all 37 ($0$): good contributes nothing to any play's vector, however often it occurs.

BM25

tf-idf leaves two properties of the count uncorrected. BM25, the weighting of current sparse retrievers and a variant in the tf-idf family (Jurafsky & Martin, 2026, §11.1.2), corrects both (Robertson & Zaragoza, 2009, §3.4):

  • Saturation. The logarithmic term frequency grows more slowly than the count, but it has no upper bound: $1 + \log_{10} \operatorname{count}(t,d)$ tends to infinity (Robertson & Zaragoza, 2009, §3.5). The occurrences of a word can show at most that the document is about the word; once that is established, further occurrences carry no information about relevance (Robertson & Zaragoza, 2009, §3.4). BM25 therefore uses a term-frequency weight that rises towards a fixed maximum.
  • Document length. A long document contains more occurrences of every word. If the author uses more words to say the same thing (verbosity), the count should be divided by the length; if the document covers more topics (scope), it should not. Real collections contain both kinds of long document, so BM25 normalises by the length only in part (Robertson & Zaragoza, 2009, §3.4).

With $|d|$ the length of document $d$ in words and $|d_{\text{avg}}|$ the average length of a document in the collection, the BM25 score of $d$ for a query $q$ is (Jurafsky & Martin, 2026, Eq. 11.12; Robertson & Zaragoza, 2009, Eq. 3.15)

$$\operatorname{score}(q,d) = \sum_{t \in q} \underbrace{\log \frac{N}{\mathrm{df}_t}}_{\text{idf}} \cdot \underbrace{\frac{\operatorname{count}(t,d)}{k_1 \left(1 - b + b\,\frac{|d|}{|d_{\text{avg}}|}\right) + \operatorname{count}(t,d)}}_{\text{saturated, length-normalised tf}}.$$

Note: The saturation is applied to the raw count $\operatorname{count}(t,d)$, not to the logarithmic $\mathrm{tf}_{t,d}$ of tf-idf: Jurafsky & Martin (2026) write $\mathrm{tf}_{t,d}$ in Eq. 11.12, but the variable of Robertson & Zaragoza (2009, §2.1) is the frequency of the word in the document.

  • $k_1 \ge 0$ sets the saturation. At $k_1 = 0$ the fraction is 1 for every query word the document contains, so only the presence of the word counts; a large $k_1$ makes the weight nearly proportional to the count. With $k_1 = 1.2$ and $b = 0$, counts of 1, 10 and 100 give 0.45, 0.89 and 0.99, against a maximum of 1; the logarithmic term frequency gives 1, 2 and 3.
  • $b \in [0, 1]$ sets the length normalisation. $b = 1$ divides the count by the relative length $|d| / |d_{\text{avg}}|$ (verbosity), $b = 0$ ignores the length (scope).
  • Usual values are $k_1 \in [1.2, 2]$ and $b = 0.75$: the values that experiments have shown reasonable when $k_1$ and $b$ are not tuned on a development collection (Manning et al., 2008, §11.4.3; Jurafsky & Martin, 2026, §11.1.2).

Sparse vs. Dense Vectors

Sparse vector (tf-idf, BM25) Dense vector (embedding)
Length $\lvert V \rvert$, 10,000–50,000 $d$, 50–1000 for word vectors (Jurafsky & Martin, 2026, §5.5)
Entries non-negative weighted counts, almost all zero real numbers, possibly negative, almost all non-zero
One dimension stands for one word of the vocabulary nothing that can be named
Obtained by counting the text training on a corpus
A query reaches a document through the words both contain similar meaning

Dense Vectors via Embedding

An embedding is a learned function that maps text to a vector in $\mathbb{R}^d$ so that semantically similar text lands nearby. In one-hot coding, by contrast, each word receives an axis of its own: every pair of words is then orthogonal, and cat is as dissimilar from kitten as it is from car. An embedding instead compresses meaning into a dense vector, in which cat and kitten are nearly aligned.

Polysemy and Homonymy

A central difficulty of natural-language processing (NLP) is that a word form need not carry one meaning:

  • Polysemy: one word with several related meanings — play as a theatrical performance against play in a sports game.
  • Homonymy: one word form with entirely unrelated meanings — the bank of a river against a financial bank.

Word Types, Word Tokens and Texts

Three answers have been given to the question what receives a vector, and they arrived in this order:

Unit What Receives a Vector How Context Is Used Example Models
Word type (Static) A word independently of its sentence Context is used only during training to create a single static lookup vector. It cannot resolve polysemy or homonymy at inference time. word2vec (Mikolov et al. 2013a), GloVe (Pennington et al. 2014), fastText (Bojanowski et al. 2017)
Word token (Dynamic) A word in a given sentence Context is processed at inference time, generating a different vector for play in a theatre sentence vs. a baseball sentence. ELMo (Peters et al. 2018), BERT (Devlin et al. 2019)
Text (Sequence) A whole sentence, passage, or document The entire sequence is compressed into one single vector that represents the meaning of the whole text. Sentence-BERT (Reimers & Gurevych 2019), nomic-embed-text (Nussbaum et al. 2025)

The word-level static models are where the geometry is easiest to derive; the text-level models are what a modern retrieval system calls.

Meaning ≈ Geometry

Because similar meanings map to nearby vectors, geometry encodes semantics:

  • Similarity = high cosine (small angle).
  • Analogies as vector arithmetic — the classic $\text{king} - \text{man} + \text{woman} \approx \text{queen}$ (the vector-offset method, Mikolov, Yih & Zweig 2013).

This property makes it possible to search by meaning instead of by keywords.

Word Embeddings and the Distributional Hypothesis

A word vector is learned from co-occurrence alone. No model in this section reads a dictionary, a parse tree or a morphological analysis; each one is a loss function built on a single assumption, the distributional hypothesis (Harris 1954; Jurafsky & Martin, 2026, ch. 5): a word is characterised by the words it occurs with.

Two training signals implement that assumption:

  1. Predict, locally — word2vec: predict a word from its neighbours, or its neighbours from it. fastText (Bojanowski et al. 2017) keeps this signal and builds the vector of a word from the vectors of its character $n$-grams.
  2. Fit the counts, globally — GloVe: fit the logarithm of a word–word co-occurrence count.

Both produce a space that is searched with the cosine similarity.

What the hypothesis costs. The same assumption that makes an embedding work sets its ceiling: a word vector records which words a word occurs with, and whether a statement containing the word is true is not among them. Similarity of vectors is therefore similarity of use, not agreement with the facts (an example is in Semantic Search as Nearest-Neighbour Search).

An embedding therefore cannot represent truth. A similarity score establishes that a text is about the right thing; it never establishes that the text is right. Every verification this course builds later — executing the code, checking the retrieved passage, asking a second model — sits outside the geometry for this reason.

CBOW and Skip-gram

CBOW and Skip-gram are the two training tasks of word2vec: both learn word vectors by predicting, inside a window of a few words, a word from its neighbours or the neighbours from a word (Mikolov et al. 2013a, §3). The prediction is only the means; the result is the vectors.

Training data. A window slides over the corpus. At position $t$ the word $w_t$ is the centre word, and the $C$ words on each side, $w_{t-C},\dots,w_{t-1},w_{t+1},\dots,w_{t+C}$, are its context. The text supplies both sides of every prediction, so no labelled data is needed. CBOW predicts the centre word from its context, Skip-gram the context from the centre word.

CBOW

CBOW (continuous bag of words) predicts the centre word from its context: the input vectors of the $2C$ context words are averaged, and the average predicts $w_t$ (Mikolov et al. 2013a, §3.1):

$$\mathbf{h}_t = \frac{1}{2C}\sum_{\substack{-C \le j \le C\\ j \ne 0}} \mathbf{v}_{w_{t+j}}, \qquad p(w_t \mid w_{t-C},\dots,w_{t+C}) = \frac{\exp(\mathbf{v}'^{\top}_{w_t}\mathbf{h}_t)}{\sum_{w \in V}\exp(\mathbf{v}'^{\top}_{w}\mathbf{h}_t)}.$$

Training maximises the average log-probability $\frac{1}{T}\sum_{t=1}^{T}\log p(w_t \mid w_{t-C},\dots,w_{t+C})$ over the $T$ words of the corpus.

  • Example ($C = 2$). In "the cat sat on the mat", the centre word sat is predicted from the average of $\mathbf{v}_{\textit{the}}$, $\mathbf{v}_{\textit{cat}}$, $\mathbf{v}_{\textit{on}}$, $\mathbf{v}_{\textit{the}}$: one prediction per position.
  • Bag of words. The average does not depend on the order of the context words, so word order inside the window is lost; the vectors themselves are continuous. Hence the name.
  • Configuration. The best reported setting uses four words on each side, $C = 4$.
w(t-2)averagew(t-1)w(t+1)w(t+2)w(t)

Skip-gram

Skip-gram predicts each context word from the centre word: the input vector of $w_t$ is the only input, and every word of the window is a separate prediction (Mikolov et al. 2013b, §2, Eq. 1–2):

$$\frac{1}{T}\sum_{t=1}^{T}\ \sum_{\substack{-C \le j \le C\\ j \ne 0}} \log p(w_{t+j} \mid w_t), \qquad p(w_{t+j} \mid w_t) = \frac{\exp(\mathbf{v}'^{\top}_{w_{t+j}}\mathbf{v}_{w_t})}{\sum_{w \in V}\exp(\mathbf{v}'^{\top}_{w}\mathbf{v}_{w_t})}.$$

  • Example ($C = 2$). In "the cat sat on the mat", the centre word sat yields four training pairs: (sat, the), (sat, cat), (sat, on), (sat, the). Each pair is one prediction, so a position costs up to $2C$ predictions instead of CBOW's one.
  • Nearer words weigh more. For each centre word a radius $R$ is drawn uniformly from $\{1,\dots,C\}$, and only the $R$ words on each side are predicted. A word at distance $j$ is therefore used with probability $(C - j + 1)/C$: always for $j = 1$, in one case out of $C$ for $j = C$. The experiments use $C = 10$ (Mikolov et al. 2013a, §3.2).
w(t)projectw(t-2)w(t-1)w(t+1)w(t+2)

Parameters of word2vec

Every word $w$ of the vocabulary $V$ has two vectors in $\mathbb{R}^d$: an input vector $\mathbf{v}_w$, used when $w$ is given, and an output vector $\mathbf{v}'_w$, used when $w$ is predicted (Mikolov et al. 2013b, §2). The model has no other weights: the trained parameters are the entries of these vectors, $2\,|V|\,d$ numbers — $6 \times 10^8$ for a vocabulary of $10^6$ words and $d = 300$. Training adjusts these entries by gradient ascent on the log-probability of the predictions; each step changes the input vectors of the words in the window and the output vectors that enter the softmax. The input vectors are the word vectors.

Why similar contexts give similar vectors. The score of a prediction is the dot product of the output vector $\mathbf{v}'_{w_O}$ of the predicted word $w_O$ with the vector of the given side: $\mathbf{v}'^{\top}_{w_O}\mathbf{h}_t$ with the context average $\mathbf{h}_t$ in CBOW, $\mathbf{v}'^{\top}_{w_O}\mathbf{v}_{w_t}$ with the input vector of the centre word in Skip-gram. Two words that occur with the same context words are trained to score high against the same output vectors, so their input vectors move towards the same region of $\mathbb{R}^d$: gradient ascent on the prediction task implements the distributional hypothesis.

Global Co-occurrence Counts: GloVe

GloVe (Global Vectors) is a word-embedding model that is fitted to how often each pair of words occurs near each other in a whole corpus, where word2vec is trained on one context window at a time (Pennington et al. 2014).

word2vec (Mikolov et al. 2013a) produces vectors whose differences encode analogies, but does not explain why. GloVe (Pennington et al. 2014) supplies the argument, and it begins with a co-occurrence table rather than a predictive model.

The word–word co-occurrence matrix $X$ has one row and one column per word of the vocabulary. Its entry $X_{ij}$ counts how often word $j$ occurs in the context of word $i$: within ten words to the left and ten to the right of an occurrence of $i$, where a pair contributes the reciprocal of its distance in words instead of 1 — 1 for neighbours, $\tfrac12$ at distance 2, $\tfrac13$ at distance 3 — so that distant pairs count less (Pennington et al. 2014, §4.2). Throughout this section $X$ is a matrix of counts, not a random variable. In "the cat sat on the mat", the occurrence of sat adds 1 to $X_{\textit{sat},\textit{cat}}$ and to $X_{\textit{sat},\textit{on}}$ (distance 1), $\tfrac12$ twice to $X_{\textit{sat},\textit{the}}$ (two occurrences at distance 2) and $\tfrac13$ to $X_{\textit{sat},\textit{mat}}$ (distance 3). The matrix is counted once over the whole corpus — the global in the name — whereas word2vec reads the windows one at a time. Let:

$$P_{ij} = P(j \mid i) = \frac{X_{ij}}{X_i}$$

where $X_i = \sum_k X_{ik}$ is the total number of times any word appears in the context of word $i$.

The ice / steam Co-occurrence Ratios

The relationship between target words $i = \textit{ice}$ and $j = \textit{steam}$ can be examined by studying the ratio of their co-occurrence probabilities with various probe words $k$ over a 6-billion token corpus:

Probability / Ratio $k=\textit{solid}$ $k=\textit{gas}$ $k=\textit{water}$ $k=\textit{fashion}$
$P(k \mid \textit{ice})$ $1.9 \times 10^{-4}$ $6.6 \times 10^{-5}$ $3.0 \times 10^{-3}$ $1.7 \times 10^{-5}$
$P(k \mid \textit{steam})$ $2.2 \times 10^{-5}$ $7.8 \times 10^{-4}$ $2.2 \times 10^{-3}$ $1.8 \times 10^{-5}$
Ratio $\frac{P(k \mid \textit{ice})}{P(k \mid \textit{steam})}$ 8.9 0.085 1.36 0.96

The ratio $\frac{P(\textit{solid} \mid \textit{ice})}{P(\textit{solid} \mid \textit{steam})}$ is much larger than 1, revealing that $\textit{ice}$ has a much stronger association with $\textit{solid}$ than $\textit{steam}$ does. Conversely, for $k = \textit{gas}$, the ratio is much smaller than 1. Ratios for non-discriminative context words ($\textit{water}$ or $\textit{fashion}$) remain close to $1$.

Compared to raw probabilities, the ratio isolates relevant words ($\textit{solid}$ and $\textit{gas}$) from noise words ($\textit{water}$ and $\textit{fashion}$). The key quantity word vectors should encode is therefore the ratio of co-occurrence probabilities, not the raw probabilities themselves.

Part III — Contextual and Text Embeddings

A contextual embedding assigns a vector to each word token, computed from the sentence in which the token occurs; a text embedding assigns one vector to a whole text, and contrastive training arranges these vectors so that cosine similarity measures the similarity of the texts.

For an agent this part decides which model computes the search vectors: the hidden states of a language model are not trained for cosine similarity, so retrieval, memory recall and tool selection need a separately trained text embedder.

From Word Types to Word Tokens

A word-type vector must average every use of the word. Consider play. Its nearest neighbours under GloVe are playing, game, games, played, players, plays, player, football, multiplayer — several parts of speech at once, and all of them sporting. The theatre sense is present in the training corpus and in the vector, but only as a small component: the vector mixes the senses in proportion to their frequency, so its nearest neighbours show the dominant sense, and every occurrence of play receives the same mixture whatever its sentence (Arora et al. 2018).

A contextual embedding assigns a vector to a word token — a word in a particular sentence — so that the vector may differ from occurrence to occurrence. ELMo, Embeddings from Language Models (Peters et al. 2018), obtains one from a bidirectional language model: a recurrent language model reading left to right and a second one reading right to left, trained jointly on the same corpus. The trained pair is then frozen and used as a feature extractor — the embedding of a token is a weighted sum of the model's own internal states at that position, one vector per layer. The nearest neighbours of a word in context are the most similar token vectors in a corpus: for play in "made a spectacular play on Alusik's grounder" the nearest token vector comes from a baseball sentence, for play in "signed to do a Broadway play" from a theatre sentence (Peters et al. 2018).

The layers of such a model are not interchangeable. Used directly as features, the lower layer tags parts of speech at 97.3 % accuracy against the top layer's 96.8, while the top layer disambiguates word senses at 69.0 $F_1$ — the harmonic mean of precision and recall — against the lower layer's 67.4. Syntax is represented low, meaning high, which is why ELMo hands the downstream task a learned weighting over all layers rather than the topmost one.

The Bidirectional Transformer Stack: BERT

BERT is a bidirectional Transformer stack: every position attends to every other position, so the vector of a token is computed from its left and its right context in one model (Devlin et al. 2019).

ELMo concatenates two models that each read in one direction; BERT (Bidirectional Encoder Representations from Transformers) replaces them by a single stack without the causal mask of a generative language model (→ L-Att), and is therefore trained as a masked language model: it predicts randomly selected input tokens from the rest of the text (Devlin et al. 2019, §3.1). Most of the text embedders in this lecture are built from such a stack, and they use two further properties of BERT.

  • The [CLS] token. Every input sequence begins with a special reserved token, [CLS] (short for classification), that stands for no word of the text. Under bidirectional attention its position reads every other position. Its final-layer vector is the input of BERT's second pre-training objective, next-sentence prediction, which decides whether two given sentences were adjacent in the corpus, so pre-training shapes that vector to carry what this one objective needs about the whole input. Downstream classification tasks (such as sentiment analysis or topic labelling) use the same vector as the input to a final linear prediction layer.
  • A frozen BERT is a feature extractor. Its hidden states are usable without further training, and, as in ELMo, the layers specialise — the context-independent input layer is far weaker than the upper ones.

A visual walkthrough of BERT, of ELMo and of the two uses of a frozen or fine-tuned BERT is given by Alammar (2018b).

From Word Vectors to Text Vectors

Retrieval compares a query with a passage, not a word with a word, so what is needed is one vector per text. The obvious construction is to run a contextual encoder over the text and reduce its token vectors to one — by taking the mean, or by taking the [CLS] vector. Measured against human similarity judgements on seven standard similarity sets, that construction fails (Reimers & Gurevych 2019; rank correlation $\times 100$):

Representation Correlation
BERT [CLS] vector 29.19
Mean of BERT token vectors 54.81
Mean of GloVe word vectors 61.32
Sentence-BERT 74.89

An untuned contextual encoder is beaten by averaged word vectors, and the [CLS] vector is far behind both. BERT's own authors state the reason in a footnote:

"The vector $C$ is not a meaningful sentence representation without fine-tuning, since it was trained with NSP." — Devlin et al. (2019), footnote 6

Here $C$ is the [CLS] output and NSP the next-sentence prediction objective: the vector is an aggregate for that task, and for no other.

Information Content and Metric Geometry

A text vector can contain the information a task needs and still be arranged so that its cosine does not measure similarity. A supervised classifier fitted on mean-pooled contextual vectors performs well because its linear layer learns a weight for each dimension and so selects the dimensions that carry the task.

Cosine similarity weights every dimension equally and has no parameters with which to make such a selection. Unless the model was trained so that similar texts lie at small angles, the cosine of two of its vectors is determined largely by dimensions that carry no information about the similarity of the texts.

An embedding model is a model whose geometry has been trained for retrieval by cosine similarity, and contrastive training is the method by which that geometry is built.

From Geometry to Systems: Bi-Encoders vs. Cross-Encoders

The cross-encoder scores a pair of texts without an embedding; comparing it with the bi-encoder shows what an embedding gains and what it gives up. The cross-encoder reads the two texts together, so every token of one text attends to every token of the other. The bi-encoder compresses each text into one vector without seeing the other text: it gives up the attention between the tokens of the two texts and gains a vector that is computed once per text, before any query, which is the property that makes search over a collection possible. Retrieval systems use both: the bi-encoder to search the collection, the cross-encoder to re-order the few best candidates of that search.

A bi-encoder computes one vector per text and scores a pair of texts by a fixed similarity function of the two vectors; a cross-encoder reads the two texts together as one sequence and outputs the score of the pair directly, without a vector for either text (Reimers & Gurevych 2019). Only the bi-encoder is an embedding model.

Cross-Encoder (Joint Scoring, No Embeddings)Text AConcat: [CLS] A [SEP] BText BTransformer Layers(self-attention over A and Bjointly)Scalar Score(0.0 - 1.0)Bi-Encoder (True Embedding Model)Text ATransformer(shared weights)Vector f(a)Text BTransformer(same weights)Vector f(b)Fixed MetricCos(f(a), f(b))Scalar Score

Cross-Encoders: Joint Attention, Non-Embedding Architecture

A cross-encoder outputs one number for a pair of texts, a similarity or relevance score: it answers how well do these two texts match? for a pair that is already given, not which texts of a collection match this one? It feeds both texts through the network together as a single concatenated sequence ([CLS] Text A [SEP] Text B).

Self-attention over the concatenated sequence lets every token of one text attend to every token of the other, in every layer; this joint reading is the source of the cross-encoder's accuracy. A cross-encoder produces no sentence embedding. The score is indecomposable—no representation is ever computed for one text in isolation. Every pair requires a full forward pass through the model:

$$\text{Cost} = \frac{n(n-1)}{2} \text{ forward passes}$$

To find the most similar pair among $n = 10{,}000$ sentences, a cross-encoder requires 49,995,000 forward passes, about 65 hours (Reimers & Gurevych, 2019).

Bi-Encoders: Decomposable Scoring & Vector Embeddings

A bi-encoder routes each text through the Transformer separately to generate independent vector embeddings $f(a)$ and $f(b)$, then compares them using a fixed, parameter-free metric like cosine similarity ($S_C$):

$$\text{score}(a,b) = S_C\big(f(a), f(b)\big)$$

By factorizing the calculation into distinct vector representations, each text is encoded once and cached:

$$\text{Cost} = n \text{ forward passes} + \text{vector comparisons}$$

For $n = 10{,}000$ sentences, this requires 10,000 encodings (about 5 seconds) plus the cosine similarities of all $n(n-1)/2$ pairs (about 0.01 seconds; Reimers & Gurevych 2019). The time falls from 65 hours to about 5 seconds because the expensive step, the forward pass, runs once per text instead of once per pair.

Sentence-BERT builds such an encoder out of BERT (Reimers & Gurevych 2019) by fine-tuning it in a siamese structure. A siamese network is one network applied to two inputs: the two Transformer boxes of the bi-encoder figure are the same network, with the same layers and the same weights — tied weights, one set of parameters applied once to text A and once to text B. A pooling layer reduces the token outputs of each pass to one vector (the mean, by default), and a training objective compares the two vectors. Because the weights are tied, both texts are mapped by the same function $f$, which is the precondition for comparing $f(a)$ with $f(b)$ by cosine, and the gradient of either pass updates the same parameters. At inference one network and the cosine remain; the second copy was never a second model.

The fine-tuning is necessary. Without it, the mean of the BERT token vectors reaches a rank correlation with human similarity judgements of 54.81 (×100), below averaged GloVe word vectors; Sentence-BERT reaches 74.89 on the same seven sets (see From Word Vectors to Text Vectors). Sentence-BERT trains on natural-language-inference labels with a classifier; current embedders train the same siamese structure with the objective of Contrastive Training.

Contrastive Training

Contrastive training shapes the geometry of a bi-encoder directly. The similarity function $S_C$ of a bi-encoder is fixed, so training can change only the vectors: a contrastive objective raises $S_C$ for matched pairs and lowers it for unmatched ones. A language-modelling loss, by contrast, trains the model to predict tokens and places no constraint on the cosine between two text vectors.

The contrastive objective in general use is InfoNCE, used for example by SimCSE (Gao, Yao & Chen 2021) and by cpt-text (Neelakantan et al., 2022).

The geometry is not discovered — it is optimised for. The training data are pairs $(q_i, p_i)$: a query and a passage that belongs to it. Write $\mathbf{q}_i,\mathbf{p}_i \in \mathbb{R}^d$ for their embeddings. Over a batch of $n$ such pairs the model minimises the InfoNCE loss — the name is from noise-contrastive estimation, learning by distinguishing a true pair from sampled noise:

$$\mathcal{L}_C = -\frac{1}{n}\sum_{i=1}^{n} \log \frac{\exp\left(S_C(\mathbf{q}_i, \mathbf{p}_i) / T\right)}{\sum_{j=1}^{n} \exp\left(S_C(\mathbf{q}_i, \mathbf{p}_j) / T\right)}$$

with $S_C$ the cosine similarity and $T > 0$ a temperature — the same quantity that sharpens a sampling distribution, and written $\tau$ in this literature.

Reading the loss. The fraction is a softmax over cosine similarities, so the expression as a whole is the cross-entropy of an $n$-way classification: which of these $n$ passages belongs to this query? What the loss does is decided by its denominator, its temperature and the sign of each term.

  • The denominator is the batch. The competitors $\mathbf{p}_j$ are the passages of the other pairs in the same batch — in-batch negatives. Nothing has to be collected in advance: each pair supplies a positive to itself and a negative to every other pair, so a batch of $n$ pairs yields $n$ classification problems with $n-1$ competitors each.
  • The temperature decides how much of the ranking is punished. Dividing by a small $T$ spreads the cosines apart before the softmax, so the loss is dominated by the single closest competitor; a large $T$ flattens them and distributes the gradient over all of them.
  • Each term has one sign. Minimising $\mathcal L_C$ raises $S_C(\mathbf{q}_i,\mathbf{p}_i)$ and lowers every $S_C(\mathbf{q}_i,\mathbf{p}_j)$: a positive pair is pulled together, everything else is pushed apart.

Alignment and uniformity. As the number of negatives grows, the two parts of $\mathcal L_C$ separate into two terms (Wang & Isola, 2020, Thm. 1): the numerator becomes an alignment term, minimal when every matched pair is mapped to the same point, and the denominator becomes a uniformity term, minimised by vectors distributed uniformly over the unit sphere.

Consequence. Cosine similarity is the search metric at inference time because it is the score the loss optimises during training. "Similarity" in vector space reflects whichever relationships were defined by the training pairs (Nussbaum et al. 2025).

Contrastive training, concretely. One training pair $(q_i, p_i)$ and one negative $p_j$:

  • $q_i$ — "How do I cancel my subscription?"
  • $p_i$ — "Steps to terminate your account membership." — the same intent, no word in common with $q_i$
  • $p_j$ — "How do I change my delivery address?" — four words in common with $q_i$, a different subject

Minimising $\mathcal L_C$ raises $S_C(\mathbf{q}_i,\mathbf{p}_i)$ above $S_C(\mathbf{q}_i,\mathbf{p}_j)$, although $p_j$ shares more words with $q_i$ than $p_i$ does. A negative chosen for its overlap with the query, like $p_j$, is a hard negative.

The Text-Embedder Family

The models named here are trained by the same contrastive principle and differ in two places: the pre-trained stack they start from, and what counts as a positive pair. The constant is not BERT — it is bidirectional attention together with contrastive training.

Model Pre-trained stack it starts from What supplies the positive pair
Sentence-BERT (Reimers & Gurevych 2019) BERT annotated natural-language-inference pairs
DPR (Karpukhin et al. 2020) two BERT towers, weights not tied question–passage pairs from question-answering data
SimCSE (Gao, Yao & Chen 2021) BERT the same sentence encoded twice, differing only by the dropout mask
E5 (Wang et al. 2024) bert-base-uncased structure in web documents — (post, comment), (title, abstract)
INSTRUCTOR (Su et al. 2023) GTR, an encoder initialised from T5 330 datasets, each side carrying a written instruction
nomic-embed-text (Nussbaum et al. 2025) a BERT variant with rotary position embeddings, 2048 tokens of context, 137 M parameters web structure, then 1.6 M labelled pairs with mined hard negatives
NV-Embed (Lee et al. 2025) Mistral-7B, a causally masked generative model, with its causal mask removed labelled retrieval and classification data

The last row locates the property. A causally masked stack — the architecture of a generative language model, in which a position attends only to the positions up to itself — is a poor embedder as it stands: the earlier tokens of a passage never see the later ones. Deleting that mask makes the model bidirectional, and the ablation reports that "the bidirectional mask consistently outperforms the causal mask" for every pooling choice (Lee et al. 2025). What an embedder needs is bidirectional attention, not a particular architecture family.

One entry in the table deviates in the score rather than in the pre-trained stack: DPR compares its two vectors by the plain inner product and not by the cosine, so a long vector can win on magnitude alone. Every other model in the table normalises and compares by cosine.

Tokenization in an Embedder

An embedder reads neither characters nor words: its input is a sequence of subword tokens, produced by the same kind of learned tokenizer a generative model uses — byte-pair encoding (Sennrich et al. 2016), or the WordPiece vocabulary of 30,000 token types that BERT uses (Devlin et al. 2019). How such a vocabulary is constructed is covered in → L-Att; three of its consequences belong here.

  • The tokenizer belongs to the checkpoint. It is fixed during pre-training, together with the embedding matrix whose rows its token identifiers index, so a model must be called with its own tokenizer and with no other. nomic-embed-text is trained on text tokenized with BERT's bert-base-uncased vocabulary (Nussbaum et al. 2025); an embedder initialised from a causally masked generative model inherits that model's vocabulary together with its weights, as NV-Embed does from Mistral-7B (Lee et al. 2025).
  • The token is the unit of every length limit. A model accepts a maximum number of tokens, not of words: nomic-embed-text is trained at 2048 tokens, and its own evaluation truncates every text to 512 (Nussbaum et al. 2025). Truncation raises no error — the part beyond the limit is simply not represented — so the chunk length of a retrieval corpus is measured in the embedder's tokens. A task prefix is ordinary text and is counted in the same budget.
  • The embedder and the generator do not share a vocabulary. They are two models with two tokenizers, so one passage has two token counts, and a chunk that fits the generating model's context window may still exceed the embedder's input.

Subword tokenization solves the problem of the unseen word. A word-type model such as word2vec or GloVe has no vector for a word outside its vocabulary. A subword tokenizer splits the word into pieces of a fixed vocabulary before the encoder sees it, so every input is representable and no word needs an entry of its own.

Semantic search returns the stored texts whose vectors have the highest cosine similarity to the vector of a query; an agent uses it for retrieval, for long-term memory and for tool selection.

Semantic search is nearest-neighbour search in the embedding space, with cosine similarity as the measure of proximity: the query and every document are embedded, and the documents whose vectors have the highest cosine similarity to the query vector are returned. Nearest refers to this similarity, not to the Euclidean distance; on unit vectors the two measures give the same ranking, since $\|\mathbf{u}-\mathbf{v}\|_2^2 = 2 - 2\,S_C(\mathbf{u},\mathbf{v})$ (see Euclidean Distance).

  1. Embed the query and every document → vectors.
  2. Score each document by cosine similarity to the query.
  3. Return the top-$k$ (the nearest neighbours).

Brute force costs $O(n\,d)$ per query over $n$ documents. That is affordable for thousands of documents; for millions it is replaced by approximate nearest-neighbour (ANN) search over a vector index (→ L-RAG).

Limits of nearest-neighbour search over embeddings.

  • Asymmetric embeddings — query and document are embedded differently by models trained with task prefixes such as search_query: and search_document:, so the two sides are not mapped by the identical function. The section Symmetric and Asymmetric Tasks treats this case.
  • Keyword blindness — dense vectors miss exact identifiers and error codes (e.g. ERR_2043); the remedy is hybrid search, a sparse keyword score (BM25, Robertson & Zaragoza 2009) + the dense one.
  • Negation — "cats like milk" and "cats do not like milk" can have a high cosine (same topic, same words) despite opposite meaning.
  • No truth value — for the query "What is the capital of Australia?", the passages "Canberra is the capital of Australia" and "Sydney is the capital of Australia" share every word but one and are about the same subject, so they can receive almost the same cosine. Whether a passage is true plays no part in the score: the false passage can rank first, and correctness is checked outside the embedding.
  • Uncalibrated scores — a cosine is meaningful within one query's ranking, not as an absolute number: a fixed cut-off such as if cos > 0.8 discards good matches for one query and admits noise for the next. Rank first, then cut by $k$ (Nussbaum et al. 2025).

Symmetric and Asymmetric Tasks

Not every use of a text embedding compares two things of the same kind, and the difference decides how the model must be called.

In a symmetric task — detecting duplicate questions, measuring semantic similarity, clustering — the two sides share structure, length and intent: two questions, two captions, two summaries. In retrieval, and therefore in RAG, they do not. A query is short, interrogative and states an information need; a passage is long, declarative and states facts. Nothing about the two texts is alike except the answer relation between them.

One encoder serving both is required to satisfy two different meanings of belongs together at once. The remedy is to tell the model which side it is encoding, and the marker has grown more expressive over time:

Model What marks the side
E5 (Wang et al. 2024) two prefixes, query: and passage:
INSTRUCTOR (Su et al. 2023) a written instruction per side — "Represent the Wikipedia question for retrieving supporting documents:" against "Represent the Wikipedia document for retrieval:"
nomic-embed-text (Nussbaum et al. 2025) four fixed prefixes — search_query, search_document, classification, clustering

For a symmetric task the two sides receive the same marker; for an asymmetric one they do not (Su et al. 2023).

A marker is not the only mechanism, and it is not an architectural one. The designs differ in where the asymmetry is placed.

  • Two encoders. Dense Passage Retrieval (DPR, Karpukhin et al. 2020) trains a separate, untied encoder for each side — $f_Q$ for questions, $f_P$ for passages, written $E_Q$ and $E_P$ in the paper — and scores a pair by the inner product $f_Q(q)^\top f_P(p)$. The asymmetry then lives in the weights rather than in the input, at the price of two networks to train and to serve.
  • One network, two roles. E5, INSTRUCTOR and nomic-embed-text share a single set of weights and break the symmetry with a string prepended to the text. The encoder has no notion that the string is a marker: it is ordinary input, and the behaviour comes entirely from training pairs that carried the same strings.

The second is what is in general use, and its two failure modes are therefore silent. The corpus and the queries must follow the same convention — a wrongly marked query raises no error, it only ranks worse — and changing the convention means re-embedding the corpus, not re-running the query.

In [2]:
# Semantic search with real embeddings via Ollama  (once: `ollama pull nomic-embed-text`)
import numpy as np
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

def embed(texts, prefix):                 # nomic-embed-text expects a task prefix
    r = client.embeddings.create(model="nomic-embed-text",
                                 input=[f"{prefix}: {t}" for t in texts])
    return np.array([d.embedding for d in r.data])

docs = ["The cat sat on the mat.",
        "A dog barked at the mailman.",
        "Python is a popular programming language."]

try:
    D = embed(docs, "search_document")                            # stored documents
    q = embed(["a feline resting on a rug"], "search_query")[0]   # the query
    sims = (D @ q) / (np.linalg.norm(D, axis=1) * np.linalg.norm(q))
    best = int(sims.argmax())
    print(f"best match ({sims[best]:.3f}): {docs[best]}")   # -> the cat sentence
except Exception as e:
    print("Error connecting to Ollama. Ensure Ollama is running and 'nomic-embed-text' is pulled.")
    print("Error details:", e)
best match (0.697): The cat sat on the mat.

Embeddings in Agents

  • Retrieval-augmented generation (RAG) — fetch documents relevant to the query and add them to the context.
  • Long-term memory — store and recall facts by similarity (→ L-Memory).
  • Tool selection — with many tools, embed the tool descriptions and retrieve only the relevant ones per request. Every tool's schema is re-sent on each call (→ L-ReAct) and the context window is finite, so this keeps the prompt small.

All three are nearest-neighbour search over embeddings, and in all three the search decides which stored texts enter the context window, which is finite and re-sent with every call.

In Practice / This Week's Lab

lecture-Embed-exercises.ipynb — calculations: cosine similarity, Euclidean distance and the inner product by hand; tf-idf and BM25 scores by hand; the vector-offset analogy, GloVe's co-occurrence ratios, the training cost of word2vec and the training pairs of CBOW and Skip-gram; the InfoNCE loss, the cost of bi- and cross-encoders, and why a pooled vector must be trained.

lecture-Embed-lab.ipynb: implement the distance functions and a brute-force nearest-neighbour search from scratch, do semantic search over tool descriptions with real embeddings (Ollama nomic-embed-text), measure the limits of nearest-neighbour search (negation, exact identifiers, a query without an answer), and check what a framework's embedder sends to the same model: task prefixes and token counts (LlamaIndex).

Summary

  • Cosine similarity = angle only (scale-invariant); Euclidean distance = straight line; on unit vectors they rank the same.
  • An embedding maps text → a vector so that meaning ≈ geometry. Three granularities, in historical order: one vector per word type (word2vec, GloVe, fastText), per word token (ELMo, BERT), per text (Sentence-BERT and the contrastively trained embedders in use today).
  • A word vector is learned from co-occurrence alone: predict the context (word2vec) or fit the logarithm of the count (GloVe).
  • A contextual encoder does not yield a text vector: an untuned [CLS] vector is a worse similarity representation than averaged word vectors. The geometry is trained, by the InfoNCE objective over cosine similarity with in-batch negatives.
  • The embedders differ in the pre-trained stack they start from — BERT, an encoder initialised from T5, even a generative model whose causal mask has been removed — and agree on bidirectional attention and that objective.
  • Semantic search = nearest neighbour by cosine, which is affordable only because a bi-encoder score factorises into one stored vector per text.
  • Symmetric tasks compare two texts of the same kind; asymmetric ones compare a short query with a long passage, and the two sides must be marked accordingly.
  • Agents use all of this for RAG, memory, tool selection.

References

Peer-reviewed papers

  • Arora, Sanjeev, et al. "Linear Algebraic Structure of Word Senses, with Applications to Polysemy." Transactions of the Association for Computational Linguistics, vol. 6, 2018, pp. 483–495. arXiv:1601.03764. — the senses of a polysemous word lie in linear superposition within its word2vec or GloVe vector, weighted by their frequency, and can be recovered by sparse coding.
  • Bojanowski, Piotr, et al. "Enriching Word Vectors with Subword Information." Transactions of the Association for Computational Linguistics, vol. 5, 2017, pp. 135–146. arXiv:1607.04606. — fastText: a word as a bag of character $n$-grams whose vectors are summed, so that related word forms share parameters and an out-of-vocabulary word still has a vector.
  • Devlin, Jacob, et al. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers). 2019, pp. 4171–4186. arXiv:1810.04805. — masked language modelling, why a bidirectional model cannot be trained on the next word, and the footnote recording that the [CLS] vector is not a sentence representation without fine-tuning.
  • Gao, Tianyu, Xingcheng Yao, and Danqi Chen. "SimCSE: Simple Contrastive Learning of Sentence Embeddings." Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing. 2021, pp. 6894–6910. arXiv:2104.08821. — the contrastive objective for sentence embeddings, applying the two diagnostics of Wang & Isola (2020) to it.
  • Harris, Zellig S. "Distributional Structure." Word, vol. 10, no. 2–3, 1954, pp. 146–162. doi:10.1080/00437956.1954.11659520. — the distributional hypothesis: a word is characterised by the contexts it occurs in, which is the assumption every word-embedding objective implements.
  • Karpukhin, Vladimir, et al. "Dense Passage Retrieval for Open-Domain Question Answering." Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing. 2020. arXiv:2004.04906. — DPR: a retrieval bi-encoder built from two untied BERT towers, and the argument that a retrieval score must be decomposable before the passage vectors can be precomputed.
  • Lee, Chankyu, et al. "NV-Embed: Improved Techniques for Training LLMs as Generalist Embedding Models." International Conference on Learning Representations. Vol. 2025. 2025. arXiv:2405.17428. — a causally masked generative model turned into an embedder by removing its causal attention mask: evidence that bidirectional attention, rather than the architecture family, is what an embedder needs.
  • Liu, Yizhou, Ziming Liu, and Jeff Gore. "Superposition Yields Robust Neural Scaling." Advances in Neural Information Processing Systems. Vol. 38. 2025. arXiv:2505.10465. — superposition: more features than dimensions, placed at small angles, and the $1/m$ scaling of the loss that the interference between them produces.
  • Mikolov, Tomas, et al. "Distributed Representations of Words and Phrases and their Compositionality." Advances in Neural Information Processing Systems. Vol. 26. 2013b. arXiv:1310.4546. — negative sampling and the subsampling of frequent words; the objective every later embedder builds on.
  • Mikolov, Tomas, et al. "Linguistic Regularities in Continuous Space Word Representations." Proceedings of the 2013 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies. 2013, pp. 746–751. ACL Anthology N13-1090. — the vector-offset method and the $\text{king}-\text{man}+\text{woman}$ analogy itself (the word2vec paper cites this one for it).
  • Nussbaum, Zach, et al. "Nomic Embed: Training a Reproducible Long Context Text Embedder." Transactions on Machine Learning Research, 2025. arXiv:2402.01613. — the model this week's demo and lab both run: the InfoNCE objective over cosine similarity, hard negatives, and the four task prefixes (search_query / search_document / classification / clustering) with the training-signal conflict that motivates them.
  • Pennington, Jeffrey, Richard Socher, and Christopher D. Manning. "GloVe: Global Vectors for Word Representation." Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP). 2014, pp. 1532–1543. ACL Anthology D14-1162. — the co-occurrence-ratio argument, the weighted least-squares fit of $\log X_{ij}$, and the reconciliation of the count-based and predict-based families.
  • Peters, Matthew E., et al. "Deep contextualized word representations." Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers). 2018, pp. 2227–2237. arXiv:1802.05365. — ELMo: a vector per word token, the play nearest-neighbour comparison, and the measured split between syntax in the lower layer and word sense in the upper one.
  • Reimers, Nils, and Iryna Gurevych. "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks." Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP). 2019, pp. 3982–3992. arXiv:1908.10084. — text → one vector: the siamese bi-encoder compared by cosine, which is what makes semantic search a nearest-neighbour problem (65 h → 5 s for the most similar pair among 10,000 sentences).
  • Robertson, Stephen, and Hugo Zaragoza. "The Probabilistic Relevance Framework: BM25 and Beyond." Foundations and Trends in Information Retrieval, vol. 3, no. 4, 2009, pp. 333–389. doi:10.1561/1500000019. — BM25, the sparse half of hybrid search.
  • Sennrich, Rico, et al. "Neural Machine Translation of Rare Words with Subword Units." Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics. 2016. arXiv:1508.07909. — byte-pair encoding: the subword vocabulary an encoder is called with, and the reason an unseen word still has a representation.
  • Su, Hongjin, et al. "One Embedder, Any Task: Instruction-Finetuned Text Embeddings." Findings of the Association for Computational Linguistics: ACL 2023. 2023, pp. 1102–1121. arXiv:2212.09741. — the symmetric versus asymmetric task distinction, and a written instruction per side as the marker that encodes it.
  • Wang, Tongzhou, and Phillip Isola. "Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere." International Conference on Machine Learning. Vol. 119. 2020. arXiv:2005.10242. — the alignment and uniformity terms the contrastive objective decomposes into.

Preprints & other non-peer-reviewed papers

  • Mikolov, Tomas, et al. "Efficient Estimation of Word Representations in Vector Space." arXiv preprint arXiv:1301.3781 (2013a). — word2vec: the CBOW and skip-gram architectures behind word-level embeddings.
  • Mitra, Bhaskar, et al. "A Dual Embedding Space Model for Document Ranking." arXiv preprint arXiv:1602.01137 (2016). — word2vec's discarded output vectors, and the nearest neighbours by input–input cosine (words of the same type) against input–output cosine (words that occur together).
  • Neelakantan, Arvind, et al. "Text and Code Embeddings by Contrastive Pre-Training." arXiv preprint arXiv:2201.10005 (2022). — contrastive training at scale, initialised from a language model, with in-batch negatives.
  • Wang, Liang, et al. "Text Embeddings by Weakly-Supervised Contrastive Pre-training." arXiv preprint arXiv:2212.03533 (2024). — E5: text pairs harvested from the structure of web documents, and the query: / passage: prefixes that break a shared encoder's symmetry.

Textbooks & monographs

  • Jurafsky, Daniel, and James H. Martin. Speech and Language Processing: An Introduction to Natural Language Processing, Computational Linguistics, and Speech Recognition with Language Models. 3rd ed., online manuscript released August 19, 2026. https://web.stanford.edu/~jurafsky/slp3/ — the distributional hypothesis, count-based word vectors, the cosine as similarity measure and word2vec (ch. 5); the bag-of-words vector, the term-document matrix, tf-idf weighting and the distinction between sparse and dense retrieval (ch. 11).
  • Manning, Christopher D., et al. Introduction to Information Retrieval. Cambridge University Press, 2008. — §6.2 the bag-of-words model; §11.4.3 Okapi BM25 and its parameter values.

Blogs, documentation & other web sources