Sub topic 4
Where Embeddings Come From: Transformer Encoders, Pooling, and Contrastive Training
This chapter assumes you know basic Python, what a vector is, and roughly what a neural network does. You do not need to train a model. The goal is a working picture of how a sentence becomes a vector, so you can predict how embedding models behave and why they fail.
The three-step recipe
Most modern embedding models follow the same recipe:
- Split the text into tokens (word pieces) and feed them to a transformer encoder.
- Collapse the encoder's per-token outputs into one vector with pooling.
- Train the whole system with a contrastive objective so that similar texts land close together.
Transformer encoders
A transformer encoder is a neural network that reads all tokens at once. Its self-attention layers let each token look at every other token, so the vector for "bank" differs in "river bank" and "bank loan". The output is one context-aware vector per token, not one per sentence.
Models like BERT and the MiniLM model used earlier in this tutorial are encoders. Their output vectors have a fixed size, such as 384 dimensions for all-MiniLM-L6-v2. Encoders also have a maximum input length, so longer text is cut off. This is why the chunking chapter matters.
Pooling: many vectors to one
Search needs one vector per text, so the per-token vectors must be combined. Three common choices:
| Method | How it works | Typical use |
|---|---|---|
| Mean pooling | Average all token vectors | Most sentence-transformers models |
| CLS pooling | Use the vector of a special first token | Some BERT-style models |
| Max pooling | Take the largest value in each dimension | Rare |
Pooling must match what the model was trained with. Switching methods on a trained model usually gives worse embeddings.
The sketch below shows mean pooling. It uses a mask so padding tokens do not affect the average.
import numpy as np
def mean_pool(token_vectors, mask):
"""token_vectors: (tokens, dims); mask: (tokens,) with 1 for real tokens, 0 for padding."""
mask = mask[:, None].astype(float)
return (token_vectors * mask).sum(axis=0) / mask.sum()
tokens = np.array([[1.0, 2.0], [3.0, 4.0], [9.0, 9.0]])
mask = np.array([1, 1, 0]) # the last row is padding
print(mean_pool(tokens, mask)) # [2. 3.]Contrastive training
A raw pretrained encoder produces poor sentence vectors, because it was trained to predict masked words, not to compare sentences. Contrastive training fixes this.
The training data is made of pairs of texts that belong together, such as a question and its answer, or a title and its article. The model processes a batch of such pairs. For each pair, the other items in the batch act as negatives, meaning texts that should not match. The loss function rewards the model for:
- Raising the similarity of each true pair.
- Lowering the similarity between each text and the unrelated texts in the batch.
Over millions of pairs, the encoder learns to place texts with related meaning near each other. Harder negatives, which look relevant but are not, teach finer distinctions.
What this means in practice
- Embeddings reflect the training data. A model trained mostly on web text may handle medical or legal jargon poorly.
- Pooling and the input length limit are fixed by the model. Use the settings its documentation gives.
- Some models were trained with prefixes such as
query:andpassage:. Skipping them can lower quality. A later chapter covers this.
Exercise
A colleague swaps mean pooling for CLS pooling on a model trained with mean pooling, hoping for faster results. Why is this risky, and what in the training process explains it?
Show answer
The contrastive training tuned the model so that the mean of its token vectors is a good sentence representation. The CLS token's vector was never optimized for that role, so the resulting embeddings are likely to be worse at placing similar texts close together. Pooling should match what the model was trained with.