Search

Search papers and lessons

Sentence Embedding

Level 3 · 12 min read

A sentence embedding maps a whole sentence to one vector so that sentences with similar meanings point in similar directions, and comparing two sentences becomes a single cosine.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Representation learning
  • Sign in to see your progress

TL;DR

A sentence embedding turns a whole sentence into one fixed-length list of numbers, so that sentences with similar meanings end up pointing in similar directions. A Transformer reads the sentence and produces a vector for each word, which are then combined into one. It is trained with Contrastive Learning on pairs of sentences known to be related, so that related pairs score high and unrelated ones low. Comparing two sentences then reduces to a single cosine.

Where you'll see it: semantic search over documents, detecting duplicate questions on a support forum, grouping customer feedback by topic, and choosing passages for question-answering systems.

Intuition

Why word vectors are not enough

A Word Embedding gives each word its own vector. A sentence, though, needs one vector, and the simplest way to get one is to average the word vectors. That fails quickly. Take two sentences, "the dog bit the man" and "the man bit the dog". They use the same words, so their averages are identical, and yet they describe opposite events. Averaging throws away order. It also struggles with negation: the average of "not good" leans toward "good".

What is needed is a way to read the words in context, so that "bit" in one sentence is combined with the words around it before the sentence is summarised. That is what the transformer provides.

What a good sentence vector does

Picture every sentence as a point in a space with a few hundred dimensions. A good sentence embedding places sentences with the same meaning close together and sentences about different things far apart. The question "how do I reset my password?" should sit near "how can I change a forgotten password?" and far from "the weather is sunny today". Once that holds, search becomes geometry: to find documents relevant to a query, embed the query and look for the nearest stored vectors.

The pipeline from sentence to vector, and then to a comparison, looks like this.

flowchart LR
  A[Sentence] --> B[Split into tokens]
  B --> C[Transformer gives one vector per token]
  C --> D[Pool the token vectors into one]
  D --> E[Sentence vector]
  E --> F[Compare with cosine]

Learn it from pairs, not labels

Nobody has labelled the "meaning" of millions of sentences. What is available is pairs: a question and the answer that followed it, two paraphrases of one fact, a premise and a sentence it logically implies. The training idea is simple. Push the two members of each pair together in the vector space, and push apart each sentence from the others in the batch. This is contrastive learning, and it turns free pairs into a training signal.

The math

From token vectors to one sentence vector

Let a sentence be a sequence of TT tokens, and let the transformer encoder produce a vector ht∈Rd\mathbf{h}_t \in \mathbb{R}^d for each token t=1,…,Tt = 1, \dots, T. Here dd is the embedding size, typically a few hundred. The vector ht\mathbf{h}_t depends on the whole sentence, because attention lets each token look at the others (see Attention Mechanism).

The sentence embedding is obtained by pooling, which means combining the token vectors into one. The most common choice is mean pooling:

u=1T∑t=1Tht.\mathbf{u} = \frac{1}{T}\sum_{t=1}^{T} \mathbf{h}_t.

Here u\mathbf{u} is the sentence vector, and the formula is simply the average of the token vectors. Padding tokens, which exist only so that sentences in a batch have equal length, are left out of the sum. Another common choice is to use the output of one special token placed at the start of the sentence. Both give a single vector for the whole sentence, and which one works better depends on how the model was trained.

Comparing two sentences

Given two sentence vectors u\mathbf{u} and v\mathbf{v}, the standard similarity is the cosine of the angle between them:

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

The dot product u⋅v\mathbf{u} \cdot \mathbf{v} is divided by the two lengths, so only the direction matters. The value is 1 when the vectors point the same way, 0 when they are perpendicular, and −1-1 when they are opposite. Many systems normalise each vector to length 1 once, after which the cosine is just the dot product, and a large collection can be searched quickly.

The contrastive objective

Take a batch of NN pairs (a1,b1),…,(aN,bN)(a_1, b_1), \dots, (a_N, b_N), where bib_i is the sentence related to aia_i. Write ui\mathbf{u}_i for the embedding of aia_i and vj\mathbf{v}_j for the embedding of bjb_j. Let sij=cos⁡(ui,vj)s_{ij} = \cos(\mathbf{u}_i, \mathbf{v}_j) be the similarity of every anchor with every candidate. The loss for the batch is

L=−1N∑i=1Nlog⁡exp⁡(sii/τ)∑j=1Nexp⁡(sij/τ).\mathcal{L} = -\frac{1}{N}\sum_{i=1}^{N} \log \frac{\exp(s_{ii}/\tau)}{\sum_{j=1}^{N} \exp(s_{ij}/\tau)}.

For each anchor aia_i, the loss is the cross-entropy of a classification over the NN candidates, where the correct class is bib_i. The symbol τ>0\tau \gt 0 is a temperature, as in Softmax Temperature: a small τ\tau makes the softmax sharper, so the loss punishes near-misses more strongly. Every other sentence in the batch serves as a negative for aia_i, which is why no separate list of unrelated sentences is needed. This form is often called InfoNCE. Minimising it raises siis_{ii} and lowers the other similarities in each row.

Worked examples

Example
Tiny: why averaging words cannot tell two sentences apart

Use toy two-dimensional word vectors: dog=(1,0)\text{dog} = (1, 0), man=(0,1)\text{man} = (0, 1), bit=(1,1)\text{bit} = (1, 1) and the=(0,0)\text{the} = (0, 0).

  1. Sentence A is "the dog bit the man". Its five tokens have vectors (0,0),(1,0),(1,1),(0,0),(0,1)(0,0), (1,0), (1,1), (0,0), (0,1).
  2. Sum them: (0+1+1+0+0,  0+0+1+0+1)=(2,2)(0+1+1+0+0,\; 0+0+1+0+1) = (2, 2).
  3. Mean pooling divides by the five tokens: uA=(0.4,0.4)\mathbf{u}_A = (0.4, 0.4).
  4. Sentence B is "the man bit the dog". It has the same five tokens, in a different order.
  5. Its sum is again (2,2)(2, 2), so uB=(0.4,0.4)\mathbf{u}_B = (0.4, 0.4).

Interpretation: the two vectors are identical, although the sentences mean opposite things. Mean pooling of static word vectors cannot see order. A transformer gives "dog" a different vector depending on whether it is the biter or the bitten, so the pooled outputs differ, and that is the reason contextual encoders replaced averaging.

Example
Standard: ranking candidates by cosine

Suppose three sentence vectors have been computed (numbers chosen for illustration):

  • Query u\mathbf{u}, "how do I reset my password": (3,4)(3, 4).
  • Candidate v\mathbf{v}, "how can I change a forgotten password": (4,3)(4, 3).
  • Candidate w\mathbf{w}, "the weather is sunny today": (−4,3)(-4, 3).
  1. Each vector has length 5: 32+42=5\sqrt{3^2 + 4^2} = 5, 42+32=5\sqrt{4^2 + 3^2} = 5 and (−4)2+32=5\sqrt{(-4)^2 + 3^2} = 5.
  2. For the first candidate, u⋅v=3×4+4×3=24\mathbf{u} \cdot \mathbf{v} = 3 \times 4 + 4 \times 3 = 24, so cos⁡(u,v)=24/(5×5)=0.96\cos(\mathbf{u}, \mathbf{v}) = 24/(5 \times 5) = 0.96.
  3. For the second candidate, u⋅w=3×(−4)+4×3=0\mathbf{u} \cdot \mathbf{w} = 3 \times (-4) + 4 \times 3 = 0, so cos⁡(u,w)=0\cos(\mathbf{u}, \mathbf{w}) = 0.
  4. Ranking by similarity puts the password sentence first, with a score of 0.96, and the weather sentence last, with 0.

Interpretation: the nearest vector is the most relevant answer, and the score gives a threshold for "close enough to call a duplicate". Note that the lengths were all 5 here. Cosine ignores length, so a long sentence and a short one can still be compared fairly.

Example
Realistic: one training step on three question pairs

A training batch holds three pairs: each question is paired with the passage that answers it. Suppose the model, at this step, gives these cosines between every anchor (rows) and every candidate (columns), with the correct candidate on the diagonal. The numbers are illustrative.

S=(0.90.10.20.20.80.00.10.10.7).S = \begin{pmatrix} 0.9 & 0.1 & 0.2 \\ 0.2 & 0.8 & 0.0 \\ 0.1 & 0.1 & 0.7 \end{pmatrix}.

Take τ=1\tau = 1 first.

  1. Row 1: the scores are 0.9,0.1,0.20.9, 0.1, 0.2. Their exponentials are 2.460,1.105,1.2212.460, 1.105, 1.221, summing to 4.7864.786. The probability on the correct candidate is 2.460/4.786=0.5142.460 / 4.786 = 0.514, so the row loss is −ln⁡0.514=0.666-\ln 0.514 = 0.666.
  2. Row 2: the scores are 0.8,0.2,0.00.8, 0.2, 0.0, with exponentials 2.226,1.221,1.0002.226, 1.221, 1.000, summing to 4.4474.447. The probability is 0.5000.500, so the loss is 0.6930.693.
  3. Row 3: the scores are 0.7,0.1,0.10.7, 0.1, 0.1, with exponentials 2.014,1.105,1.1052.014, 1.105, 1.105, summing to 4.2244.224. The probability is 0.4770.477, so the loss is 0.7410.741.
  4. The batch loss is the mean: (0.666+0.693+0.741)/3=0.700(0.666 + 0.693 + 0.741)/3 = 0.700.
  5. Now take τ=0.05\tau = 0.05. Row 1 becomes the scores 0.9/0.05=180.9/0.05 = 18, 22 and 44. The correct candidate's probability is 1/(1+e−16+e−14)1/(1 + e^{-16} + e^{-14}), which is about 1−0.00000081 - 0.0000008, so the row loss is about 0.0000010.000001.

Interpretation: every row already has its correct candidate at the top, so the model ranks each question's answer first. At τ=1\tau = 1 the softmax is soft: the correct candidate gets only about half the probability, so the loss is 0.70 and the model still gets a strong push. At τ=0.05\tau = 0.05 the same ranking gives a loss close to zero, because the gaps between scores are magnified twenty-fold. The temperature changes how hard the loss punishes a near-miss, not which candidate is ranked first.

Tradeoffs and failure modes

A sentence embedding is a compression. It is very good at the question "are these about the same thing?" and weaker at questions that depend on fine detail.

SituationProblemBetter choice
Negation or opposite meaning"The film was good" and "the film was not good" often land close togetherUse a cross-encoder (a model that reads both sentences together) to re-rank, or train with hard negatives (negatives that look similar to the anchor, such as the same sentence with a negation added)
Short question against a long passageA model trained mostly on short pairs can represent long text poorly, and the two lengths may not match wellSplit long documents into passages and embed each one
Specialised domain, such as clinical notes or legal textA general model has not seen the vocabulary and the relations that matterFine-tune (continue training) on in-domain pairs
Duplicate or near-duplicate pairs in the batchA true match is treated as a negative (a false negative), which weakens the signalDeduplicate the batch, or sample pairs so that each anchor's negatives are truly different
Millions of documents to searchComparing the query with every stored vector is slowAn approximate nearest-neighbour index
The embedding model is upgradedOld and new vectors live in different spaces and cannot be comparedRe-embed the whole collection, and store the model version with each vector

The fixed-length bottleneck matters most for long inputs. A paragraph of two hundred words is squeezed into one vector of a few hundred numbers, and the details that do not dominate the meaning are lost first. Two sentences that differ only in a number, a date or a negation can receive almost the same vector. When such detail decides the answer, a Bi-Encoder used for fast retrieval should be followed by a slower, more careful model that reads the query and candidate together.

History

Word vectors came first. Tomáš Mikolov and colleagues showed in 2013 that simple models trained on large text could place words in a space where related words are close (see Efficient Estimation of Word Representations in Vector Space (word2vec)). Sentence-level vectors took longer. Early methods such as skip-thought vectors trained a recurrent network to predict neighbouring sentences in 2015, and InferSent in 2017 trained a sentence encoder on the labelled task of natural-language inference, where a pair of sentences is marked as entailing, contradicting or neutral.

The Universal Sentence Encoder, released by Google in 2018, showed that one general-purpose encoder could serve many tasks. Then BERT appeared, and it was strong at word-level tasks, but its raw output averaged over tokens was poor at measuring similarity between sentences. Reimers and Gurevych fixed this in 2019 with Sentence-BERT, which used a shared BERT encoder for both sentences, pooled the outputs and trained on labelled sentence pairs. Their model made sentence comparison fast enough for search over large collections. In 2021 Gao and colleagues showed that a simple contrastive objective, using dropout (randomly switching off parts of the network) to make two slightly different views of the same sentence, produced strong sentence embeddings.

The idea caught on because it turns the vast amount of unlabelled pairs on the web into training data, and because a vector comparison is cheap enough to run at scale. It is now the basis of most semantic search and retrieval systems.

Recap

A sentence embedding is produced in three steps: a transformer gives each token a context-aware vector, pooling combines them into one sentence vector, and the model is trained with a contrastive loss so that related sentences have high cosine similarity and unrelated ones have low similarity. The cosine of two vectors is the measure of relatedness. The result depends on the temperature, the choice of negatives and the pooling method. The embeddings feed directly into bi-encoder retrieval, and the same contrastive idea appears in representation learning for images and audio.

Check yourself

QuestionWhy does averaging static word vectors fail to distinguish 'the dog bit the man' from 'the man bit the dog'?Show answer

Both sentences contain the same tokens, so their sums and their means are identical. Averaging is invariant to word order, so it cannot tell the two sentences apart. A contextual encoder fixes this by giving each word a vector that depends on its neighbours, so the pooled outputs differ.

QuestionTwo sentence vectors are (1,0)(1, 0) and (1,1)(1, 1). What is their cosine similarity, and what does it say about them?Show answer

The dot product is 11, the lengths are 11 and 2\sqrt{2}, so cos⁡=1/2≈0.707\cos = 1/\sqrt{2} \approx 0.707. The vectors point about 45 degrees apart, so the sentences are related but not identical in direction.

QuestionIn a contrastive batch with N=4N = 4 pairs, why does each anchor get three negatives without any extra labelling?Show answer

Each anchor's own partner is the positive, and the partners of the other three anchors in the same batch are treated as negatives. They are unrelated sentences by construction, so no extra annotation is needed. The cost is that a near-duplicate in the batch becomes a false negative.

QuestionYou lower the temperature τ\tau in the contrastive loss from 1 to 0.05. What changes, and what risk comes with it?Show answer

The softmax becomes sharper, so scores that differ slightly are separated by much larger factors. A correct top ranking then gives almost zero loss, and a near-miss is punished more strongly. The risk is that a very small temperature makes the gradients large and the training unstable, and it magnifies the effect of false negatives.

Sources