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.
After this week you can:
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:
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 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] $$
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.
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}")
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).
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.
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):
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.
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):
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.
| 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 |
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.
A central difficulty of natural-language processing (NLP) is that a word form need not carry one meaning:
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.
Because similar meanings map to nearby vectors, geometry encodes semantics:
This property makes it possible to search by meaning instead of by keywords.
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:
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 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 (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.
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})}.$$
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.
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 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.
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.
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.
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.
[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 visual walkthrough of BERT, of ELMo and of the two uses of a frozen or fine-tuned BERT is given by Alammar (2018b).
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.
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.
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.
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).
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 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.
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$:
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 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.
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.
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).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.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).
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.
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.ERR_2043);
the remedy is hybrid search, a sparse keyword score (BM25, Robertson & Zaragoza 2009)
+ the dense one.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).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.
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.
# 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)
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.
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).
[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.Peer-reviewed papers
[CLS] vector is not a sentence representation without fine-tuning.search_query / search_document / classification / clustering) with the training-signal conflict that motivates them.Preprints & other non-peer-reviewed papers
query: / passage: prefixes that break a shared encoder's symmetry.Textbooks & monographs
Blogs, documentation & other web sources
OllamaEmbedding, which prepends a task prefix only when query_instruction or text_instruction is set.embed_query and embed_documents, and the providers onto whose task marker they are mapped.