By Sagi Shaier · 8 November 2026 · 10 min read
Sentence embeddings and semantic similarity
How an encoder turns a whole sentence into one vector with mean pooling, how cosine similarity scores two of those vectors, and how the scores are trained, thresholded and evaluated, with runnable PyTorch.
A sentence embedding is a list of numbers, a vector, that a model produces for a whole sentence so that sentences with similar meanings get similar vectors. Semantic similarity is the task of scoring how close two texts are in meaning, and the usual way to do it is to embed both texts and compare their vectors. Duplicate-question detection, grouping similar support tickets and "related articles" lists are built on it. Models read text as tokens, which can be whole words or pieces of words.
A vector as the model output
Many NLP tasks return something a person reads: a label, a tag for each token, or an answer copied from a passage. Feature extraction returns a vector instead, and another piece of code uses that vector next. It might compare it with another vector, find the closest stored vectors or feed it to a small classifier.
The numbers in the vector are learned, not written by hand. A model trained for this puts similar texts near each other in vector space, so "how close are these two vectors?" becomes a stand-in for "how close are these two texts in meaning?". The length of the vector is a design choice of the model. It can be any size, and 384 or 768 are common.

From token vectors to one sentence vector
A word embedding gives one vector to each token id, looked up from a table of learned rows. A sentence embedding needs one vector for the whole text, and it is built in three steps:
- Each token id is looked up in the embedding table, giving one vector per token.
- An encoder, a network that reads the whole sequence, turns those into contextual token vectors. Each token's vector now depends on the tokens around it, so "bank" gets a different vector in "river bank" and "bank account".
- A pooling step combines the token vectors into one vector for the sentence.
If the sentence has $T$ tokens and each vector has $d$ numbers, the first two steps produce a $T \times d$ table and pooling turns it into $d$ numbers.

Mean pooling with a mask
Mean pooling averages the token vectors. Texts in a batch have different lengths, so shorter ones are padded with filler tokens to match the longest one. Those padding positions are not part of the sentence and should not be averaged in.
A mask marks which positions are real. Write $h_t$ for the token vector at position $t$ and $m_t$ for its mask value, 1 for a real token and 0 for padding:
$$h = \frac{\sum_t m_t h_t}{\sum_t m_t}$$
The top sums only the real token vectors and the bottom counts the real tokens, so $h$ is the average over real tokens. For example, a text with real token vectors $[1, 2, 0]$ and $[3, 0, 2]$ plus two padding positions pools to $[2, 1, 1]$.

In PyTorch the mask arrives as attention_mask, the name Hugging Face uses, with shape (batch, seq_len):
1import torch
2
3
4def mean_pooling(token_embeddings, attention_mask):
5 mask = attention_mask.unsqueeze(-1).float() # (batch, seq_len, 1)
6 summed = (token_embeddings * mask).sum(dim=1) # (batch, hidden_size)
7 counts = mask.sum(dim=1).clamp(min=1) # (batch, 1)
8 return summed / counts
9
10
11# one text with 2 real tokens and 2 padding positions, hidden size 3
12token_embeddings = torch.tensor([[[1.0, 2.0, 0.0],
13 [3.0, 0.0, 2.0],
14 [0.5, 0.5, 0.5],
15 [0.5, 0.5, 0.5]]])
16attention_mask = torch.tensor([[1, 1, 0, 0]])
17
18print(mean_pooling(token_embeddings, attention_mask))
19print(token_embeddings.mean(dim=1)) # averaging the padding too1tensor([[2., 1., 1.]])
2tensor([[1.2500, 0.7500, 0.7500]])unsqueeze(-1) adds a last dimension of size 1 so the mask can multiply every number in each token vector. Multiplying zeroes out the padding vectors, sum(dim=1) adds across positions, and the division by the count of real tokens gives the average. clamp(min=1) avoids dividing by zero for an empty text. The second line shows what goes wrong without the mask: the padding pulls the vector to $[1.25, 0.75, 0.75]$.

Getting sentence vectors with Hugging Face
The Hugging Face feature-extraction pipeline wraps the tokenizer and the encoder call:
1from transformers import pipeline
2
3extractor = pipeline(
4 "feature-extraction",
5 model="sentence-transformers/all-MiniLM-L6-v2",
6)
7
8vectors = extractor([
9 "a man is slicing bread",
10 "someone cuts a loaf",
11])Check the shape of what comes back. Some checkpoints return one vector per token, which still needs the pooling step above. Tools built for sentence embeddings usually return one vector per sentence. The model card says which one you get.

Feature extraction in seven questions
A useful way to describe an NLP task is to answer seven questions about it: the input, the target, the prediction, the data, training, inference and evaluation. The post on NLP tasks explains each one. For feature extraction the prediction is the vector itself, and the target depends on how the encoder was trained. Similar pairs can be trained to sit close together, matching queries and documents to score high, or labels to be easy to predict from the vector.

Sentence similarity: how close in meaning?
Sentence similarity is the two-text use of those vectors: encode text A, encode text B and compute one score for how close they are. The output is a score, not a label and not a span.
Datasets for it often rate pairs on a 0 to 5 scale. "A man is slicing bread" and "Someone cuts a loaf" should score high. "A man is slicing bread" and "A plane is landing" should score low.

Cosine similarity compares directions
The usual score for two sentence vectors $u$ and $v$ is cosine similarity. The top of the fraction is the dot product $u \cdot v$, the sum of the products of matching entries. The bottom multiplies the two vector lengths $\|u\|$ and $\|v\|$, where a vector's length is the square root of the sum of its squared entries:
$$\cos(u, v) = \frac{u \cdot v}{\|u\| \|v\|}$$
Dividing by both lengths removes the effect of size, so the score depends only on the angle between the vectors. Vectors pointing the same way score 1, vectors at a right angle score 0, and vectors pointing in opposite directions score -1.
For example, with $u = [3, 4]$ and $v = [4, 3]$ the dot product is $3 \cdot 4 + 4 \cdot 3 = 24$ and both lengths are 5, so the cosine is $24 / 25 = 0.96$:
1import torch
2
3
4def cosine_similarity(u, v):
5 numerator = (u * v).sum()
6 denominator = u.norm() * v.norm()
7 return (numerator / denominator).item()
8
9
10u = torch.tensor([3.0, 4.0])
11for v in ([4.0, 3.0], [6.0, 8.0], [-4.0, 3.0], [-3.0, -4.0]):
12 print(v, round(cosine_similarity(u, torch.tensor(v)), 2))1[4.0, 3.0] 0.96
2[6.0, 8.0] 1.0
3[-4.0, 3.0] 0.0
4[-3.0, -4.0] -1.0$[6, 8]$ is twice as long as $u$ and points the same way, so it scores 1. .norm() is a vector's length and .item() turns the one-number tensor into a Python float.

A sentence-pair model
A sentence-similarity system runs the same encoder on both sentences. Sharing the encoder puts both vectors in the same space, which is what makes comparing them meaningful.
1emb_a = mean_pooling(encoder(ids_a), mask_a)
2emb_b = mean_pooling(encoder(ids_b), mask_b)
3score = F.cosine_similarity(emb_a, emb_b)emb_a and emb_b both have shape (batch, hidden_size), and score has shape (batch,), one score per pair. Here is the last line on random vectors standing in for 8 pooled pairs:
1import torch
2import torch.nn.functional as F
3
4torch.manual_seed(0)
5emb_a = torch.randn(8, 384) # 8 pooled sentence vectors
6emb_b = torch.randn(8, 384) # their 8 partner sentences
7score = F.cosine_similarity(emb_a, emb_b)
8print(emb_a.shape, score.shape)1torch.Size([8, 384]) torch.Size([8])The encoder can be used as it is, as a feature extractor, or trained further on sentence pairs.

Training on labeled pairs
Two kinds of labels are common, and each has its own loss.
When pairs have a numeric rating, such as a 0 to 5 score scaled to 0 to 1, the model predicts a cosine score and is trained with a regression loss, the squared gap between that score and the label $y$:
$$L = (\cos(u, v) - y)^2$$
When pairs are labeled duplicate or not, with $y = 1$ for duplicates and $y = 0$ otherwise, a contrastive loss can be used. It has a margin $m$:
$$L = y(1 - \cos(u, v)) + (1 - y)\max(0, \cos(u, v) - m)^2$$
For a duplicate pair only the first term is active, and it falls as the cosine rises toward 1. For a non-duplicate pair only the second term is active, and it is 0 once the cosine drops below $m$. The margin stops training from pushing unrelated pairs apart forever.
1import torch
2
3
4def regression_loss(cos, y):
5 return (cos - y) ** 2
6
7
8def contrastive_loss(cos, y, m=0.5):
9 return y * (1 - cos) + (1 - y) * torch.clamp(cos - m, min=0) ** 2
10
11
12pairs = [(0.86, 1.0), (-0.27, 0.0), (0.70, 0.0)] # (cosine score, label)
13for cos, y in pairs:
14 cos, y = torch.tensor(cos), torch.tensor(y)
15 print(f"cos={cos:.2f} y={y:.0f} regression={regression_loss(cos, y):.4f} contrastive={contrastive_loss(cos, y):.4f}")1cos=0.86 y=1 regression=0.0196 contrastive=0.1400
2cos=-0.27 y=0 regression=0.0729 contrastive=0.0000
3cos=0.70 y=0 regression=0.4900 contrastive=0.0400The unrelated pair at -0.27 is already below the margin, so the contrastive loss ignores it. The non-duplicate pair at 0.70 sits above the margin and still adds loss. With either loss, the gradient updates change the encoder so related texts move closer in vector space and unrelated ones move apart.

Turning a score into a decision
A product that needs a yes or no answer, such as "is this question a duplicate?", compares the score with a threshold:
1score = cosine_similarity(vec_a, vec_b)
2is_duplicate = score >= 0.85The threshold is a product choice. A high one gives fewer false duplicate matches and misses some real paraphrases. A lower one catches more paraphrases and marks more unrelated texts as duplicates. For example, here are five pairs with scores from 0.93 down to 0.30:
1scores = [0.93, 0.88, 0.81, 0.62, 0.30]
2for threshold in (0.85, 0.75):
3 print(threshold, [s >= threshold for s in scores])10.85 [True, True, False, False, False]
20.75 [True, True, True, False, False]Moving the threshold from 0.85 to 0.75 adds the pair at 0.81. Whether that is a catch or a false match depends on what the pair really is, which is why the threshold is usually tuned on labeled pairs.

Evaluating similarity scores
When the dataset has human scores, the question is whether the model's scores move with them. Two correlations answer it, and both range from -1 to 1:
- Pearson correlation checks whether the model scores follow the human scores along a straight line. If humans rate one pair much higher than another, Pearson rewards the model for showing a gap of the same proportion.
- Spearman correlation checks only the order. It is Pearson computed on the ranks of the scores, so it asks whether pairs humans rated higher get higher model scores, whatever the exact numbers.
1import torch
2
3
4def pearson(x, y):
5 x, y = x - x.mean(), y - y.mean()
6 return ((x * y).sum() / (x.norm() * y.norm())).item()
7
8
9def ranks(x):
10 return x.argsort().argsort().float() # rank of each value, 0 = smallest (no ties here)
11
12
13human = torch.tensor([0.0, 1.0, 2.0, 4.0, 5.0]) # 0 to 5 ratings for 5 pairs
14model = torch.tensor([0.10, 0.20, 0.30, 0.70, 0.95]) # cosine scores for the same pairs
15print(round(pearson(human, model), 3), round(pearson(ranks(human), ranks(model)), 3))10.986 1.0The model puts all five pairs in the same order as the humans, so Spearman is 1.0. The gaps between its scores are not exactly proportional to the human gaps, so Pearson is a little lower. When the labels are duplicate or not instead of scores, precision, recall and F1 on the thresholded decisions are the usual metrics.

Sentence similarity in seven questions
The same seven-question checklist describes sentence similarity. The input is two texts, the target is a rating or a duplicate label, and the prediction is a cosine score.

Sentence embeddings in practice
The sentence-transformers library loads checkpoints that were trained so their pooled vectors work well with cosine similarity, and its encode method does the tokenizing, encoding and pooling in one call:
1from sentence_transformers import SentenceTransformer
2
3model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
4sentences = [
5 "a man is slicing bread",
6 "someone cuts a loaf",
7]
8embeddings = model.encode(sentences, convert_to_tensor=True)
9score = cosine_similarity(embeddings[0], embeddings[1])The steps are the ones above: encode each text into one vector, then compare the two vectors with cosine similarity.

When to use sentence embeddings, and common mistakes
Sentence embeddings fit when you need to compare texts by meaning. Common uses are finding duplicate questions or tickets, grouping similar texts and recommending related articles. Matching a user request to a stored example is another one.
Mistakes that come up often:
- Averaging over padding. Pooling without the mask changes the vector of every padded text in a batch, more so for short texts.
- Comparing vectors from different models. Two different encoders produce vectors in unrelated spaces, so their cosine says little about meaning. Encode both texts with the same model and the same pooling.
- Using a model that was not trained for sentence similarity. Mean-pooling any encoder's token vectors gives a sentence vector, and checkpoints trained on sentence pairs usually give vectors that work better with cosine similarity.
- Picking a threshold without data. 0.85 is an example, not a rule. Tune it on labeled pairs from your own texts.
- Reporting only Pearson. If the use case only needs the right order, Spearman is the more relevant number.
Related concepts
Retrieval repeats the same comparison between one query and many candidate texts and returns the best matches first. It is explained in retrieval and text ranking. Natural language inference, explained in natural language inference (NLI), also takes two sentences, but it reads them together and returns a label: entailment, contradiction or neutral. A similarity model encodes each sentence on its own and returns a score. Text classification, covered in text classification explained, can run on top of sentence embeddings by putting a small classifier on the vector.
QuiddityML teaches feature extraction and sentence similarity as two concepts in the Intro to NLP track, and the exercises on them include filling in masked mean pooling, spotting the pooling bug that averages over padding and turning the cosine similarity formula into code.