Embedding models: one vector per sentence
"When will my parcel arrive?" and "How many days does delivery take?" share no words, yet they mean the same thing. An embedding model turns these two sentences into nearby vectors. This page splits the road from one sentence to one vector into two steps you can try.
Short answer. An embedding model reads a sentence, makes one vector per token, then gathers them into one (pooling), and is trained separately so that sentences with the same meaning get close vectors and different sentences get distant ones.
Scaled-down toy. The token vectors are 2D values placed by hand to explain the idea. A real model's vectors have far more dimensions and are set by training.
Press Next to put the tokens into the average one row at a time. The green circle is the average so far, the orange arrow is how far it moved this step, the faint circle is where it was, and the gray dashed line is the gap to the new token. Choose "First token ([CLS])" to take the first row as it is.
Definitions
The text below explains with pictures and labs. These are the textbook definitions. When a text is cut into n tokens, hi is the vector of token i after the whole encoder, and s is the sentence vector.
- embedding model
- A model that takes one piece of text and gives one vector with a fixed number of dimensions (a sentence embedding). It is trained so that texts with similar meanings get vectors that are close together. Usually an encoder makes one vector per token, and pooling joins them into one.
- pooling
- An operation that joins the token vectors h1, …, hn into one vector. Mean pooling takes the average of each entry (the formula below). CLS pooling takes the last-layer output of the special token [CLS] added at the front, as it is.
- contrastive learning
- A way to train a model with a loss that pulls together the embeddings of pairs with the same meaning (positive pairs) and pushes apart the embeddings of texts that are not a pair (negatives). Sometimes an anchor, a positive and a negative are used as one group (a triplet).
- bi-encoder
- A structure that reads two texts separately with the same model (the same weights) to get vectors u and v, and then compares the vectors with a similarity, often cosine similarity. The vectors for one side can be computed ahead of time and stored.
- cross-encoder
- A structure that joins two texts into one input and puts them into the model together, so the two texts see each other inside the model, and the model gives one score directly. It has to run the model for every pair, so nothing can be computed ahead of time.
1. First, one vector per token
The body of an embedding model is an encoder. It cuts the sentence into tokens (tokenization), takes a vector for each token from the embedding table (embedding table), and rewrites those vectors at every layer. An encoder like BERT rewrites them by looking at both the left and the right context in all layers (source ②). So the "parcel" vector that comes out at the end holds not the word "parcel" alone but "parcel" in this sentence (contextual embeddings). The encoder-only branch is covered in encoders and decoders.
What is left at the end is one vector per token. Six tokens give six rows. To compare sentences in search, you need one row per sentence. Gathering many rows into one is pooling.
What is different. The experiment in section 9 of the embeddings page also took an average. That was an average of word vectors taken from the embedding table (they know nothing about context). Here it is an average of token vectors after the whole encoder (they have seen the whole sentence). The math is the same, but the vectors going in are different.
2. Pooling: many rows into one
Two methods are common. They are the two buttons in the experiment above.
Mean. Add each position and divide by the number of tokens.
s = (h₁ + h₂ + … + hₙ) ÷ n
s: the sentence vector (the one row you get)hᵢ: the vector of token i (after the whole encoder)n: the number of tokens
The experiment computes it by adding one row at a time. The end result is the same.
mₖ = mₖ₋₁ + (hₖ − mₖ₋₁) ÷ k
mₖ: the average after k tokens.mₙ = shₖ − mₖ₋₁: the gap from the current average to the new token (the gray dashed line)÷ k: move only 1/k of that gap (the orange arrow). The more tokens are already in, the less one new token moves the average
First token ([CLS]). Put a special token [CLS], which is not a word, at the very front of the sentence, and use its row at the end as the sentence vector. On its way through the layers this token has looked at every other token of the sentence (attention), so it can be trained to stand for the whole sentence.
Try this. ① Press Next seven times. The average moves (−0.4, 2.2) → (0.9, 1.3) → (0.73, 1.13) → (0.8, 1.45) → (1.04, 1.48) → (0.9, 1.4), and at the end the sum (5.4, 8.4) ÷ 6 = (0.9, 1.4) becomes the sentence vector. ② At step 4 the average moves only 1/4 of the gap toward "my" (1, 2.4). At step 6, "arrive" moves it only 1/6. ③ Switch to "First token ([CLS])" and the sentence vector is (−0.4, 2.2). Its cosine similarity with the mean (0.9, 1.4) is 0.731. The same token vectors give a different vector when you gather them differently. That is why you follow the pooling the model was set up with.
Pooling only gathers. Nothing in pooling makes two sentences with the same meaning land close together. The training in the next section does that.
3. Why similar sentences get close: separate training on pairs
Sentence-BERT (SBERT) in source ① modifies a pretrained BERT with siamese and triplet network structures to get sentence embeddings with meaning that can be compared using cosine similarity. A siamese structure reads two sentences separately with the same model (the same weights). A triplet uses three sentences as one set: an anchor sentence, its pair, and a sentence that is not its pair. You collect many pairs of sentences with the same meaning, then adjust the vectors so that pairs move closer and non-pairs move apart. The experiment below shows that one step at a time.
- A1 When will my parcel arrive?
- A2 How many days does delivery take?
- B1 I forgot my password.
- B2 I want to set a new login code.
- C1 I want a refund.
- C2 Can I get my money back?
- D1 What time does the store open?
- D2 When do your business hours start?
Sentences with the same letter (like A1 and A2) are pairs, joined by a gray dashed line. Next is one training step. The solid green arrow is the pull toward the pair, and the dashed orange arrow is the push from the one of the other 6 that pushes hardest. The arrows are drawn longer than the real move so you can see the direction, and the dot moves by the pull plus all 6 pushes. The faint circle is where the dot was, and the light lines from the origin are the directions cosine looks at. The starting positions are made-up values placed by hand.
The value the experiment tries to make small (the loss) is this.
L = n̄ − p̄
L: the loss. Smaller is betterp̄: the average cosine similarity of the pairs (4 pairs)n̄: the average cosine similarity of the non-pairs (the other 24 couples)
For L to go down, p̄ must go up and n̄ must go down. At each step every dot moves a little against the slope of the loss (gradient descent).
u ← u − η × ∂L/∂u, ∂cos(u, v)/∂u = v ÷ (|u| |v|) − cos(u, v) × u ÷ |u|²
u: the dot (vector) of one sentence.v: the dot of the other sentence it is compared withη: the step size. 6 in this experiment∂L/∂u: how much and which way L changes when u moves a little (the slope). The part from the pair term is the green arrow, the largest single part from the non-pair terms is the orange arrowcos(u, v): cosine similarity.|u|is the length of u (dot product and cosine)- The second formula is the slope of the cosine. Moving u this way raises the cosine of u and v fastest. It turns the direction of u, seen from the origin, toward v
Try this. ① At the start, the average cosine of the pairs is −0.61 and of the non-pairs −0.063. The pairs are actually farther apart. The loss is 0.547. ② Press Next three times and the pairs' average reaches 0. ③ After 12 steps, the pairs are at 0.964, the non-pairs at −0.295, and the loss is −1.258. Each pair has gathered in one direction, and the four groups have spread to different directions around the origin. ④ The orange arrow shows only the hardest push of the 6 non-pairs. There are 24 non-pair couples, so each one weighs 1/6 of a pair, and the 6 pushes come from different sides and partly cancel. So in the first step, every dot is pushed less than 1/4 as far as it is pulled.
To be honest. This loss L = n̄ − p̄ is a small formula made to show "pairs closer, non-pairs apart". It is not the loss of any particular paper. Also, real training does not move the dots directly. It changes the model's weights (backpropagation), and then the vector you get when the same sentence is read again moves the way these arrows point.
4. Two towers and one tower
There are two shapes for scoring how similar two sentences are.
Source ① notes that to compare a sentence pair with BERT, both sentences have to be fed into the network. That is the one-tower way. Then finding the most similar pair among 10,000 sentences means running the model for every pair. The number of pairs is 10,000 × 9,999 ÷ 2 = 49,995,000, about 50 million. Source ① says this takes about 50 million inference computations, about 65 hours with BERT, and about 5 seconds with SBERT, which uses two towers. Two towers run the model only once per sentence, and the rest is cosine similarity between vectors, which is cheap.
The price is that in two towers the two sentences never see each other inside the model. Each sentence's meaning is squeezed into one vector before they are compared. Why one tower is more precise, and how to use it for reranking, is in reranking in hybrid search.
5. When to use which
| Option | Good | Bad | Use it for |
|---|---|---|---|
| Two towers (bi-encoder) | Document vectors are stored ahead of time; when a query comes in, only the query is read and compared. Fast even with many documents (about 5 seconds in the 10,000-sentence example) | The two sentences never see each other inside the model, so it is less precise than one tower | Searching widely across many documents first (vector search), the search step of RAG |
| One tower (cross-encoder) | Reads the two sentences together, so it is more precise | Nothing can be computed ahead of time; the model runs for every pair (about 50 million times, about 65 hours, in the 10,000-sentence example) | Re-scoring the few candidates a wide search picked (reranking) |
So the two are often chained. Search widely with two towers, then re-score only the top few with one tower.
Frequently asked
Is pooling enough to get a sentence embedding?
You get one vector. But pooling does not make sentences with the same meaning land close together. Pooling only gathers rows. That guarantee comes from separate training on pairs of sentences with the same meaning.
Should I use the mean or [CLS]?
Use whatever the model you use was set up with. The same token vectors give different results with the two methods. In this page's experiment, the cosine similarity between the two results is 0.731.
What is the difference between a bi-encoder and a cross-encoder?
A bi-encoder reads the two sentences separately, makes one vector for each, and compares them with cosine similarity. Document vectors can be computed ahead of time, so it is used to search widely across many documents. A cross-encoder reads the two sentences together and gives one score. It is more precise but has to run again for every pair, so it is used to rerank a short list.
Words
| What this page says | What books call it |
|---|---|
| Embedding model | embedding model, sentence encoder |
| One vector per token | token embeddings, the output of the last layer |
| Gathering many rows into one | pooling. Mean pooling, CLS pooling |
| Two towers | bi-encoder. Reading separately with the same model is a siamese network |
| One tower | cross-encoder |
| A set of anchor, pair and non-pair | triplet |
| Pair · non-pair | positive pair · negative |
| Training that pulls pairs and pushes non-pairs | contrastive learning |
| The value to make small | loss |
| Step size | learning rate |
| Re-scoring a short list | reranking |
Sources
- ① Reimers, Gurevych (2019). Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. The abstract says that comparing with BERT needs both sentences fed into the network, gives the most-similar-pair numbers for 10,000 sentences (about 50 million computations, about 65 hours → about 5 seconds), and describes siamese and triplet structures for sentence embeddings compared with cosine similarity.
- ② Devlin et al. (2018). BERT (arXiv 1810.04805). The abstract says the model conditions jointly on both left and right context in all layers.
← Encoders and decoders: three kinds of transformerHow LLMs are trained →