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 tokens, and let the transformer encoder produce a vector for each token . Here is the embedding size, typically a few hundred. The vector 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:
Here 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 and , the standard similarity is the cosine of the angle between them:
The dot product 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 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 pairs , where is the sentence related to . Write for the embedding of and for the embedding of . Let be the similarity of every anchor with every candidate. The loss for the batch is
For each anchor , the loss is the cross-entropy of a classification over the candidates, where the correct class is . The symbol is a temperature, as in Softmax Temperature: a small makes the softmax sharper, so the loss punishes near-misses more strongly. Every other sentence in the batch serves as a negative for , which is why no separate list of unrelated sentences is needed. This form is often called InfoNCE. Minimising it raises and lowers the other similarities in each row.
Worked examples
Use toy two-dimensional word vectors: , , and .
- Sentence A is "the dog bit the man". Its five tokens have vectors .
- Sum them: .
- Mean pooling divides by the five tokens: .
- Sentence B is "the man bit the dog". It has the same five tokens, in a different order.
- Its sum is again , so .
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.
Suppose three sentence vectors have been computed (numbers chosen for illustration):
- Query , "how do I reset my password": .
- Candidate , "how can I change a forgotten password": .
- Candidate , "the weather is sunny today": .
- Each vector has length 5: , and .
- For the first candidate, , so .
- For the second candidate, , so .
- 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.
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.
Take first.
- Row 1: the scores are . Their exponentials are , summing to . The probability on the correct candidate is , so the row loss is .
- Row 2: the scores are , with exponentials , summing to . The probability is , so the loss is .
- Row 3: the scores are , with exponentials , summing to . The probability is , so the loss is .
- The batch loss is the mean: .
- Now take . Row 1 becomes the scores , and . The correct candidate's probability is , which is about , so the row loss is about .
Interpretation: every row already has its correct candidate at the top, so the model ranks each question's answer first. At 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 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.
| Situation | Problem | Better choice |
|---|---|---|
| Negation or opposite meaning | "The film was good" and "the film was not good" often land close together | Use 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 passage | A model trained mostly on short pairs can represent long text poorly, and the two lengths may not match well | Split long documents into passages and embed each one |
| Specialised domain, such as clinical notes or legal text | A general model has not seen the vocabulary and the relations that matter | Fine-tune (continue training) on in-domain pairs |
| Duplicate or near-duplicate pairs in the batch | A true match is treated as a negative (a false negative), which weakens the signal | Deduplicate the batch, or sample pairs so that each anchor's negatives are truly different |
| Millions of documents to search | Comparing the query with every stored vector is slow | An approximate nearest-neighbour index |
| The embedding model is upgraded | Old and new vectors live in different spaces and cannot be compared | Re-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 and . What is their cosine similarity, and what does it say about them?Show answer
The dot product is , the lengths are and , so . The vectors point about 45 degrees apart, so the sentences are related but not identical in direction.
QuestionIn a contrastive batch with 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 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
- Reimers and Gurevych, Sentence-BERT (2019): https://arxiv.org/abs/1908.10084
- Gao, Yao and Chen, SimCSE (2021): https://arxiv.org/abs/2104.08821
- Cer et al., Universal Sentence Encoder (2018): https://arxiv.org/abs/1803.11175
- Devlin et al., BERT (2018): https://arxiv.org/abs/1810.04805