“If it is sunny tomorrow, we will go hiking” and “We will go hiking if tomorrow is a sunny day” mean the same thing. “How old are you?” and “What is your age?” share almost no words, yet ask the same question. Recognizing when two pieces of text mean the same thing, or something close, is one of the most useful abilities in NLP.
This reading covers where text similarity is used, how it is evaluated, why simply taking embeddings from a pretrained BERT model works surprisingly poorly, and how Sentence-BERT fixes this by training sentence embeddings so that cosine similarity becomes meaningful.
1Why text similarity?
The goal: given two texts, output a score for how similar their meanings are. A good similarity function shows up everywhere:
- Document clustering: group a pile of unlabeled documents into topics (technology, entertainment, sports) by putting similar documents together.
- Information retrieval: rank documents by how well they match a search query.
- Recommendation: suggest items whose descriptions or reviews are similar to what a user liked.
- Evaluating generated text: check that a paraphrase keeps the original meaning, that a style-transferred sentence still says the same thing, or detect plagiarism.
- In-context example selection: when prompting a language model with demonstrations, pick the training examples most similar to the test input. This often works better than choosing examples at random (Liu et al., 2022).
2Evaluating similarity: the STS benchmark
The Semantic Textual Similarity (STS) benchmark (Cer et al., 2017) contains sentence pairs from news, captions, and forums, each annotated by people with a similarity score from 0 (completely unrelated) to 5 (equivalent meaning):
| Sentence 1 | Sentence 2 | Human | A model |
|---|---|---|---|
| A soccer player is kicking the soccer ball into the goal from a long way down the field. | A soccer player kicks the ball into the goal. | 3.25 | 3.94 |
| Earlier this month, RIM had said it expected to report second-quarter earnings of between 7 cents and 11 cents a share. | Excluding legal fees and other charges it expected a loss of between 1 and 4 cents a share. | 1.2 | 0.5 |
| David Beckham Announces Retirement From Soccer. | David Beckham retires from football. | 4.4 | 3.8 |
A model produces its own score for each pair. We do not require its scores to equal the human scores exactly (a model's cosine similarities are on a different scale anyway). Instead we measure how well the two lists of scores agree, using a correlation coefficient.
Pearson and Spearman correlation
Pearson's correlation measures how well the points fall on a straight line:
$$r = \frac{\sum_i (x_i-\bar x)(y_i-\bar y)}{\sqrt{\sum_i (x_i-\bar x)^2}\,\sqrt{\sum_i (y_i-\bar y)^2}},$$ranging from $-1$ (perfect negative line) through $0$ (no linear relationship) to $+1$ (perfect positive line).
Spearman's correlation is Pearson's correlation computed on the ranks instead of the raw scores. It asks only whether the two lists put the pairs in the same order, so it measures any monotonic relationship, linear or not. STS results are usually reported with Spearman correlation, because what matters is that more similar pairs get higher scores, not the exact scale.
3First attempts
The general recipe: encode each sentence into a vector, then compare the vectors with cosine similarity:
$$E_1=\text{Encoder}(S_1),\quad E_2=\text{Encoder}(S_2),\qquad \text{Similarity}(S_1,S_2)=\frac{E_1\cdot E_2}{\|E_1\|\,\|E_2\|}.$$Word overlap
The simplest encoder is a bag-of-words or TF-IDF vector. Cosine similarity then measures word overlap. This captures topic, but it fails in two directions:
- Different words, same meaning: “How old are you?” and “What is your age?” share only one word, so their similarity is low.
- Same words, different meaning: “The dog bit the man” and “The man bit the dog” have identical word counts, so their similarity is exactly 1.
Pretrained BERT embeddings
A natural next step: use a pretrained BERT model as the encoder, taking either the output vector of the [CLS] token or the average of all token output vectors. Surprisingly, this performs poorly on STS, sometimes worse than simply averaging GloVe word vectors. Two reasons:
- BERT was never trained to make cosine similarity meaningful. Its pretraining objectives (masked language modeling and next sentence prediction) never ask that sentences with similar meanings have nearby vectors. A representation can be excellent for classification after fine-tuning and still be a poor similarity measure.
- The vectors are crowded together. Pretrained BERT embeddings occupy a narrow cone in the vector space, so almost every pair of sentences has a high cosine similarity, and the differences between related and unrelated pairs are tiny.
bert-base-uncased; the sentence embedding values with all-MiniLM-L6-v2, a Sentence-Transformers model trained for similarity. Bag of words uses raw word counts (lowercased, punctuation removed). Colors use the same scale for every encoder, so notice how uniformly high BERT [CLS] is.4Sentence-BERT
Sentence-BERT (SBERT; Reimers & Gurevych, 2019) fine-tunes BERT specifically to produce sentence embeddings whose cosine similarity reflects meaning. The key idea is a siamese network: the same BERT model (shared weights) encodes each sentence separately, followed by a pooling layer (usually mean pooling) that produces one vector per sentence, $u$ and $v$.
Training data: natural language inference
SBERT is trained on the Stanford Natural Language Inference (SNLI) dataset (and its multi-genre extension MNLI). Each example is a premise, a hypothesis, and a label saying whether the hypothesis follows from the premise:
| Premise | Hypothesis | Label |
|---|---|---|
| A boy is jumping on skateboard in the middle of a red bridge. | The boy does a skateboarding trick. | entailment |
| The boy is wearing safety equipment. | neutral | |
| The boy skates down the sidewalk. | contradiction |
Predicting these labels requires understanding meaning, which is exactly what the embeddings should capture.
Training objectives
- Classification objective (training): concatenate $u$, $v$, and their element-wise difference $|u-v|$, and feed this into a softmax classifier over the three labels, trained with cross-entropy: $$o=\text{softmax}\big(W_t\,[u;\,v;\,|u-v|]\big).$$ The classifier is only a training device; it is discarded afterwards.
- Triplet objective: given an anchor sentence $s_a$, a positive sentence $s_p$ (similar to it), and a negative sentence $s_n$ (not similar), train the embeddings so that the anchor is closer to the positive than to the negative by at least a margin $\epsilon$: $$\mathcal{L}=\max\big(\|s_a-s_p\|-\|s_a-s_n\|+\epsilon,\ 0\big).$$ With NLI data, an entailed hypothesis can serve as the positive and a contradicting one as the negative.
Using the model (inference)
After training, each sentence is encoded independently and compared with cosine similarity; a value close to 1 means similar meaning. Training pulled paraphrases together in the embedding space and pushed unrelated sentences apart.
Results
Average Spearman correlation (×100) over seven STS datasets, without using any STS training data (Reimers & Gurevych, 2019, Table 1):
| Model | Avg. Spearman |
|---|---|
| BERT [CLS] vector | 29.19 |
| Average BERT embeddings | 54.81 |
| Average GloVe embeddings | 61.32 |
| InferSent (GloVe) | 65.01 |
| Universal Sentence Encoder | 71.22 |
| SBERT-NLI-base | 74.89 |
| SBERT-NLI-large | 76.55 |
Raw BERT embeddings are worse than averaged GloVe vectors; after SBERT training, the same BERT model is the best of all.
5Bi-encoders vs. cross-encoders
There is another way to use BERT for similarity: feed both sentences into BERT together, separated by [SEP], and predict a score from the output. This cross-encoder lets every word of one sentence attend to every word of the other, so it is usually more accurate. SBERT is a bi-encoder: each sentence is encoded alone.
| Cross-encoder | Bi-encoder (SBERT) | |
|---|---|---|
| Input | both sentences together | each sentence separately |
| Accuracy | higher | slightly lower |
| Cost to compare $n$ sentences | one BERT pass per pair: $n(n-1)/2$ | one BERT pass per sentence: $n$ |
| Reusable vectors | no | yes: encode once, store, compare cheaply |
In practice the two are often combined: a fast bi-encoder retrieves a short list of candidates from millions of documents, and a cross-encoder re-ranks that short list. This is the basis of modern semantic search and of the retrieval step in retrieval-augmented generation.
6In practice and beyond
The Sentence-Transformers library makes this a few lines of code:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
emb = model.encode(["The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium."]) # shape (3, 384)
print(model.similarity(emb, emb)) # 3 x 3 cosine similarities
- Contrastive learning: later methods such as SimCSE train embeddings by pulling a sentence close to a slightly perturbed copy of itself and pushing it away from other sentences in the batch.
- Modern embedding models (e.g., E5, BGE, and commercial embedding APIs) are trained on far more pairs, and are compared on the MTEB benchmark, which covers retrieval, clustering, classification, and STS.
- Limitations remain. In Figure 2, the sentence embedding model still gives “The dog bit the man” and “The man bit the dog” a similarity of 0.98: one vector per sentence can blur details such as who did what to whom.
7Summary
- Text similarity powers clustering, retrieval, recommendation, evaluation of generated text, and example selection.
- STS benchmarks compare model scores with human 0–5 ratings using Spearman correlation, which only cares about the order.
- Word-overlap similarity misses paraphrases; pretrained BERT embeddings are poor similarity measures because BERT was never trained for it and its vectors are crowded together.
- Sentence-BERT fine-tunes a siamese BERT on NLI data (classification or triplet objective), so cosine similarity between its embeddings reflects meaning.
- Bi-encoders are fast and reusable; cross-encoders are more accurate; retrieval systems often combine both.
8Practice
Exercise 1: Spearman by hand
Human scores for three pairs are $[4.5, 1.0, 3.0]$ and model scores are $[0.9, 0.7, 0.2]$. Rank both lists (1 = highest) and decide whether Spearman correlation is perfect.
Exercise 2: bag-of-words cosine
Using raw word counts, compute the cosine similarity of “how old are you” and “what is your age”, and of “the dog bit the man” and “the man bit the dog”.
Exercise 3: cost
You want to find, for each of 1,000 user questions, the most similar of 100,000 FAQ entries. How many BERT passes does a cross-encoder need? A bi-encoder?
Quick quiz
9Further reading
- Reimers & Gurevych (2019). Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. EMNLP.
- Sentence-Transformers documentation. (Tutorials, pretrained models, and semantic search examples.)
- Gao, Yao & Chen (2021). SimCSE: Simple Contrastive Learning of Sentence Embeddings. EMNLP.
- MTEB Leaderboard. (Compares current text embedding models.)
- Cer, Diab, Agirre, Lopez-Gazpio & Specia (2017). SemEval-2017 Task 1: Semantic Textual Similarity. (The STS benchmark.)