◆ AI All-in-One

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
↗ Plan a path here

Read first

BERT and Encoder ModelsWord Embeddings

This leads to

CLIP and Contrastive Learning
The full path from zero — 30 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Word Embeddings
  21. Vanishing and Exploding Gradients
  22. Normalization Layers: BatchNorm and LayerNorm
  23. LSTMs and GRUs
  24. Residual Connections
  25. Sequence-to-Sequence Models
  26. Attention
  27. Self-Attention and Multi-Head Attention
  28. Positional Encodings
  29. The Transformer
  30. BERT and Encoder Models
  31. 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:

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 do I reset my password? I forgot my login details. Best pizza in Rome? Where to eat in Naples? My account is locked. small angle → similar meaning password vs login: 7° apart, cos ≈ 0.99 large angle → unrelated login vs pizza: 48° apart, cos ≈ 0.67 (real embeddings have hundreds of dimensions, where unrelated texts are usually much closer to 90° apart) origin
Fig. 1 Sentences placed in a (here two-dimensional) embedding space. Paraphrases point in nearly the same direction and have cosine similarity near 1; unrelated sentences point in very different directions. Real embeddings have hundreds of dimensions; this picture is a sketch.

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 u\mathbf{u} and v\mathbf{v} are is cosine similarity, the cosine of the angle between them (Dot Product, Norms and Similarity):

cos⁡(u,v)=u⋅v∥u∥ ∥v∥\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert}

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" =(0.8,0.5,0.1)= (0.8, 0.5, 0.1), length 0.64+0.25+0.01=0.949\sqrt{0.64 + 0.25 + 0.01} = 0.949
  • B "forgot my login" =(0.7,0.6,0.2)= (0.7, 0.6, 0.2), length 0.49+0.36+0.04=0.943\sqrt{0.49 + 0.36 + 0.04} = 0.943
  • C "best pizza in Rome" =(0.1,−0.2,0.9)= (0.1, -0.2, 0.9), length 0.01+0.04+0.81=0.927\sqrt{0.01 + 0.04 + 0.81} = 0.927

Then cos⁡(A,B)=(0.56+0.30+0.02)/(0.949×0.943)=0.88/0.895=0.98\cos(A, B) = (0.56 + 0.30 + 0.02)/(0.949 \times 0.943) = 0.88/0.895 = 0.98, while cos⁡(A,C)=(0.08−0.10+0.09)/(0.949×0.927)=0.07/0.880=0.08\cos(A, C) = (0.08 - 0.10 + 0.09)/(0.949 \times 0.927) = 0.07/0.880 = 0.08. 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 (ai,bi)(a_i, b_i) 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 nn pairs. For anchor aia_i, its partner bib_i is the positive, and the other n−1n-1 texts bjb_j in the batch serve as negatives for free. Compute all n×nn \times n similarities, divide by a temperature τ\tau (often around 0.05), and apply ordinary softmax cross-entropy with the correct "class" for row ii being column ii. This is the InfoNCE loss:

Li=−log⁡exp⁡ ⁣(cos⁡(ai,bi)/τ)∑j=1nexp⁡ ⁣(cos⁡(ai,bj)/τ)L_i = -\log \frac{\exp\!\big(\cos(a_i, b_i)/\tau\big)}{\sum_{j=1}^{n} \exp\!\big(\cos(a_i, b_j)/\tau\big)}
b1 Paris is… b2 Simmer 8 min… b3 ≈300,000 km/s b4 Shakespeare… a1 Q: capital of France? 0.82 0.11 0.05 0.14 a2 Q: boil an egg? 0.09 0.77 0.12 0.03 a3 Q: speed of light? 0.07 0.15 0.85 0.10 a4 Q: who wrote Hamlet? 0.16 0.02 0.08 0.80 diagonal: true pairs, pushed up. Off-diagonal: in-batch negatives, pushed down. each row is a softmax classification over the batch; cosine similarities are illustrative
Fig. 2 In-batch negatives for a batch of four pairs. Each row is an anchor, each column a candidate. The loss pushes the diagonal (true pairs) up and every off-diagonal cell (other pairs in the batch) down, like a classification with one correct class per row.

Worked example. One anchor, a batch of 3 candidates, τ=0.1\tau = 0.1. Cosine similarities to the positive and two negatives: 0.8,0.3,0.10.8, 0.3, 0.1. Divided by τ\tau: 8,3,18, 3, 1. Softmax probability of the positive: e8/(e8+e3+e1)=2981/(2981+20.1+2.7)=0.992e^8 / (e^8 + e^3 + e^1) = 2981 / (2981 + 20.1 + 2.7) = 0.992, so the loss is −ln⁡0.992=0.008-\ln 0.992 = 0.008: the model already gets this one right. If the positive only scored 0.3 and a negative 0.8, the loss would be about 5.05.0, 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: and passage: , 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

  1. Compute cos⁡(B,C)\cos(B, C) for the three vectors in the worked example.
  2. 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"?
  3. Change the batch size from 128 to 8 (and the arange to match). How does the final retrieval@1 change, and why do fewer in-batch negatives matter?

Hint for 2: at τ=1\tau = 1, cosine similarities between −1 and 1 give softmax probabilities that are all very similar, so the gradient barely distinguishes right from wrong.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Embeddings A = (0.8, 0.5, 0.1) and B = (0.7, 0.6, 0.2) have cosine similarity about 0.98; A and C = (0.1, −0.2, 0.9) about 0.08. What does that tell you?

  2. You must search a million documents for every user query. Why use a bi-encoder rather than a cross-encoder for the first pass?

  3. In contrastive training with in-batch negatives, where do the negatives come from?

  4. You switch to a newer embedding model but keep the old document vectors in your index. What happens?

  5. A user searches for "error code 4012" and gets documents about other error codes. What does the chapter suggest?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Sentence Transformers documentation

UKP Lab & Hugging Face · Beginner · Free

The standard Python library for computing, training and fine-tuning sentence embeddings, with many pretrained models and examples.

Paper

Sentence-BERT

Reimers & Gurevych · 2019 · Advanced · Free

Siamese BERT networks that produce useful sentence embeddings.

Paper

MTEB: Massive Text Embedding Benchmark

Muennighoff et al. (Hugging Face) · 2022 · Intermediate · Free

A benchmark of embedding models across many tasks (retrieval, clustering, classification, similarity) and languages, with a public leaderboard.

Paper

Matryoshka Representation Learning

Kusupati et al. · 2022 · Advanced · Free

Trains embeddings so that their first few dimensions already work well on their own, letting you truncate vectors to save storage.

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

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