Level 3 In-Depth AI · Transformers and Language Models
Sentence Embeddings
Turning a whole sentence, paragraph or document into a single vector so that texts with similar meanings land close together. How these vectors are trained with contrastive learning, and how they power semantic search, retrieval and clustering.
- Level
- ●●●●● Intermediate
- Reading
- 11 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 30 concepts →
- Quiz
- 5 questions ↓
This leads to
CLIP and Contrastive LearningThe full path from zero — 30 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Word Embeddings
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- BERT and Encoder Models
- Sentence Embeddings
Read them roughly in this order. See it on the concept map →
Why it matters
Computers compare numbers easily and meanings hardly at all. "How do I reset my password?" and "I forgot my login details" share almost no words, yet mean nearly the same thing. A keyword search would miss the match.
A sentence embedding is a single vector, typically a few hundred to a few thousand numbers, that represents the meaning of a whole piece of text. An embedding model is trained so that texts with similar meanings get vectors that point in similar directions. Then "how similar are these two texts?" becomes "what is the angle between these two vectors?", which is a fast calculation.
This one idea powers a lot of applied AI:
- Semantic search: find documents by meaning, not keywords (Embeddings and Semantic Search).
- Retrieval-augmented generation: find the passages an LLM should read before answering (Retrieval-Augmented Generation), stored in a vector database.
- Clustering and topic discovery, duplicate detection, recommendation and classification with very little labelled data.
Word embeddings gave one vector per word. Sentence embeddings do the same for whole texts, and the leap in quality came from training them with contrastive learning on pairs of related texts.
The intuition
Imagine a huge library where books are shelved not by author or title but by meaning: every book about baking bread sits together, slightly separate from cake recipes, and very far from car-repair manuals. To find books related to the one in your hand, you just look at its neighbours.
An embedding model builds that library in a space with hundreds of dimensions. Each text becomes a point (or arrow from the origin); related texts are neighbours.
How does the model learn where to put things? By being shown pairs that should be close (a question and its answer, a sentence and its paraphrase, a title and its article) and pushed to put them closer together than any of the other texts in the same batch. That is contrastive learning: learning by comparison.
Key idea A sentence embedding model maps a text to one vector so that similar meaning → small angle. It is trained contrastively: pull matching pairs together, push non-matching ones apart. Compare embeddings with cosine similarity.
How it works
Cosine similarity
The standard measure of how close two embeddings and are is cosine similarity, the cosine of the angle between them (Dot Product, Norms and Similarity):
It is 1 when the vectors point the same way, 0 when they are at right angles (unrelated), and −1 when they point in opposite directions. If you first scale every embedding to length 1 (normalise it), cosine similarity is just the dot product, which is what fast vector search uses.
Worked example. Three tiny 3-dimensional embeddings:
- A "reset my password" , length
- B "forgot my login" , length
- C "best pizza in Rome" , length
Then , while . A and B are near-paraphrases; C is unrelated.
From token vectors to one vector: pooling
An encoder such as BERT outputs one vector per token. To get one vector per text, you pool them:
- Mean pooling: average all the token vectors (ignoring padding). The most common choice.
- CLS pooling: use the vector of the special first token.
- Last-token pooling: for decoder-based embedding models, use the final token's vector, since in a causal model only it has seen the whole text.
Pooling alone is not enough. A key finding of the Sentence-BERT paper (Reimers and Gurevych, 2019) was that averaging the outputs of an off-the-shelf BERT gave poor sentence similarity, worse on their benchmarks than simply averaging older GloVe word vectors. BERT was never trained to make whole-sentence vectors comparable. Fine-tuning for that purpose is what makes the difference.
Bi-encoders and cross-encoders
There are two ways to use a Transformer to judge how related two texts are:
- A cross-encoder feeds both texts together into one model, which outputs a relevance score. Attention can compare every word of one with every word of the other, so it is accurate. But nothing can be precomputed: to compare a query with a million documents, you run the model a million times.
- A bi-encoder encodes each text separately into an embedding and compares embeddings with cosine similarity. Document embeddings can be computed once and stored, so a search costs one model call for the query plus a fast vector lookup.
The Sentence-BERT paper put numbers on it: finding the most similar pair among 10,000 sentences with a BERT cross-encoder would take about 65 hours, versus about 5 seconds with their bi-encoder. Production search systems typically combine both: a bi-encoder retrieves the top 100 candidates, and a cross-encoder (a reranker) re-orders them (Advanced RAG).
Contrastive training
Training data for contrastive learning consists of positive pairs that should be close: question–answer, query–clicked document, title–body, sentence–paraphrase, or two halves of the same web page. Modern embedding models are pretrained on hundreds of millions of such naturally occurring pairs, then fine-tuned on smaller curated sets.
The trick that makes it efficient is in-batch negatives. Take a batch of pairs. For anchor , its partner is the positive, and the other texts in the batch serve as negatives for free. Compute all similarities, divide by a temperature (often around 0.05), and apply ordinary softmax cross-entropy with the correct "class" for row being column . This is the InfoNCE loss:
Worked example. One anchor, a batch of 3 candidates, . Cosine similarities to the positive and two negatives: . Divided by : . Softmax probability of the positive: , so the loss is : the model already gets this one right. If the positive only scored 0.3 and a negative 0.8, the loss would be about , a strong push to fix it.
Bigger batches mean more negatives and usually better embeddings. Hard negatives, texts that look similar but are not matches (for a question about Python lists, a passage about Python dictionaries), are added deliberately because random negatives become too easy.
SimCSE (2021) found a remarkably simple unsupervised version: pass the same sentence through the encoder twice. Dropout makes the two embeddings slightly different, and treating them as a positive pair, with the rest of the batch as negatives, already trains good sentence embeddings.
Modern embedding models
Since about 2022, general-purpose embedding models (open families such as E5, BGE, GTE and Nomic, and commercial APIs from OpenAI, Cohere, Google, Voyage and others) are trained in large multi-stage contrastive pipelines, and some recent ones are built on decoder-only LLMs. Practical features to know:
- Query and document prefixes. Some models expect instructions such as
query:andpassage:, because questions and documents are different kinds of text. Using the wrong prefix quietly hurts results. - Matryoshka embeddings (2022) are trained so that the first 64, 128, 256… dimensions already form a good embedding, letting you truncate vectors to save storage.
- Multilingual models map texts in different languages into the same space, so an English query can find a French document.
The MTEB benchmark (Massive Text Embedding Benchmark, 2022) evaluates embedding models across retrieval, clustering, classification, reranking, semantic similarity and other tasks in many languages. Its public leaderboard is the usual starting point for choosing a model, but scores on your own data matter more.
In code
A from-scratch contrastive training run on synthetic data. Each "meaning" is a hidden vector; a "sentence" is a noisy, distorted view of it, and two calls give two paraphrases. We train a small encoder with in-batch negatives and measure how often a sentence's nearest neighbour among 500 held-out sentences is its paraphrase.
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
n_meanings, d_in = 2000, 64
meanings = torch.randn(n_meanings, 16)
mix = torch.randn(16, d_in)
def sentence(m): # two calls = two paraphrases
return torch.tanh(m @ mix) + 0.8 * torch.randn(len(m), d_in)
encoder = nn.Sequential(nn.Linear(d_in, 128), nn.ReLU(), nn.Linear(128, 32))
def embed(x): return F.normalize(encoder(x), dim=-1) # unit length: dot product = cosine
def retrieval_at_1(n=500):
"""How often is a sentence's nearest neighbour its own paraphrase?"""
m = meanings[-n:] # held-out meanings, never trained on
with torch.no_grad():
a, b = embed(sentence(m)), embed(sentence(m))
return ((a @ b.T).argmax(1) == torch.arange(n)).float().mean().item()
print(f"before training: retrieval@1 = {retrieval_at_1():.2f}")
opt = torch.optim.Adam(encoder.parameters(), lr=1e-3)
for step in range(1500):
m = meanings[torch.randint(0, n_meanings - 500, (128,))] # a batch of 128 meanings
a, b = embed(sentence(m)), embed(sentence(m)) # paraphrase pairs
logits = a @ b.T / 0.05 # cosine similarities / temperature
loss = F.cross_entropy(logits, torch.arange(128)) # InfoNCE: match i with i
opt.zero_grad(); loss.backward(); opt.step()
print(f"after training: retrieval@1 = {retrieval_at_1():.2f} (chance = {1/500:.3f})")
# before training: retrieval@1 = 0.19
# after training: retrieval@1 = 0.85 (chance = 0.002)
The InfoNCE loss is literally cross_entropy on the similarity matrix with the diagonal as the targets. The trained encoder also works on meanings it never saw, which is what makes embeddings useful for search over new documents.
With a real pretrained model, the Sentence Transformers library does everything in a few lines (it downloads a small model, so it is not run here):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # a small, fast English model
docs = ["How do I reset my password?", "I forgot my login details.",
"Where is the best pizza in Rome?"]
emb = model.encode(docs, normalize_embeddings=True) # shape (3, 384)
print(model.similarity(emb, emb)) # 3 x 3 cosine similarity matrix
Common pitfalls
- Using raw BERT or LLM hidden states as embeddings. Without contrastive fine-tuning they work poorly. Use a model trained for embeddings.
- Mixing models. Embeddings from different models, or different versions of one model, live in different spaces and can't be compared. Re-embed everything when you switch.
- Ignoring prefixes and instructions that the model card asks for.
- Truncation. Most embedding models have a maximum input length (often 512 tokens, longer for newer ones). Text beyond it is silently cut. Split long documents into chunks (Retrieval-Augmented Generation).
- Similarity is not relevance. Embeddings capture topical similarity. "Is aspirin safe in pregnancy?" and "Aspirin is unsafe in pregnancy" and "Aspirin is safe in pregnancy" can all be close. Rerank, and let an LLM read the actual text.
- Trusting a leaderboard over your data. Build a small test set of real queries and known-good documents and measure retrieval on it.
Watch out Embedding similarity is weak at negation, numbers and exact identifiers. A search for "error code 4012" may return documents about other error codes. Combine embedding search with keyword search (hybrid search) when exact terms matter.
Variations
- Sparse embeddings (such as SPLADE) produce long, mostly-zero vectors over the vocabulary, combining keyword precision with learned expansion.
- Late interaction models such as ColBERT keep one vector per token and compare token by token, sitting between bi-encoders and cross-encoders in cost and accuracy.
- Multimodal embeddings put images and text in the same space: CLIP and Contrastive Learning.
- Binary and quantised embeddings store each dimension in 1 or 8 bits to make huge indexes cheap.
- Building search on top of all this: Embeddings and Semantic Search, Vector Databases, Retrieval-Augmented Generation.
A bit of history
Early sentence vectors included Paragraph Vector (doc2vec, 2014), Skip-Thought (2015), Facebook's InferSent (2017, trained on natural-language-inference pairs) and Google's Universal Sentence Encoder (2018). In 2019 Nils Reimers and Iryna Gurevych published Sentence-BERT, fine-tuning BERT in a siamese (shared-weight) bi-encoder setup, and released the sentence-transformers library, which became the standard tool. Dense Passage Retrieval (Facebook AI, 2020) showed that a contrastively trained bi-encoder with in-batch negatives could beat classic keyword search (BM25) for open-domain question answering. SimCSE (2021) simplified contrastive training, and OpenAI's embedding API (2022) brought embeddings to many developers. The MTEB benchmark (2022) gave the field a common scoreboard, and the rise of RAG from 2023 made embedding models one of the most widely deployed kinds of model.
Try it
- Compute for the three vectors in the worked example.
- In the training code, change the temperature from 0.05 to 1.0. What happens to retrieval@1? Why does a high temperature make the task too "soft"?
- Change the batch size from 128 to 8 (and the
arangeto match). How does the final retrieval@1 change, and why do fewer in-batch negatives matter?Hint for 2: at , cosine similarities between −1 and 1 give softmax probabilities that are all very similar, so the gradient barely distinguishes right from wrong.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Sentence Transformers documentation
The standard Python library for computing, training and fine-tuning sentence embeddings, with many pretrained models and examples.
Sentence-BERT
Siamese BERT networks that produce useful sentence embeddings.
SimCSE: Simple Contrastive Learning of Sentence Embeddings
Contrastive sentence embeddings where the positive pair is the same sentence passed twice with different dropout masks.
MTEB: Massive Text Embedding Benchmark
A benchmark of embedding models across many tasks (retrieval, clustering, classification, similarity) and languages, with a public leaderboard.
Dense Passage Retrieval for Open-Domain Question Answering
Showed that learned dense embeddings beat BM25 keyword search for finding passages that answer questions, the foundation of embedding-based retrieval.
Text Embeddings by Weakly-Supervised Contrastive Pre-training (E5)
Contrastive pretraining on hundreds of millions of naturally occurring text pairs, the recipe behind many modern general-purpose embedding models.
Matryoshka Representation Learning
Trains embeddings so that their first few dimensions already work well on their own, letting you truncate vectors to save storage.
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/sentence-embeddings.md