QuiddityML

By · 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.

The sentence The quick brown fox jumps over the lazy dog goes through an encoder into a dense vector h with values such as 0.21, -0.37 and 0.58. The vector feeds a cosine similarity score of 0.82, a search index returning the top documents, and a small classifier.

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:

  1. Each token id is looked up in the embedding table, giving one vector per token.
  2. 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".
  3. 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.

Tokens The, quick, brown, fox, jumps through to the full stop each get a token vector (T x d), the encoder turns them into contextual token vectors (T x d), and pooling combines them into one sentence vector of size d.

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]$.

Token vectors h1 to h3 have mask value 1 and the padding vectors h4 and h5 have mask value 0. Only the first three are averaged, sum divided by count(mask), into the sentence vector.

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 too
1tensor([[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]$.

Shapes in the pooling code: token_embeddings B x T x H times the attention mask unsqueezed to B x T x 1, summed over T to B x H, divided by the counts B x 1, giving sentence_vector B x H.

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.

A list of N texts goes through a tokenizer (input_ids and attention_mask, both B x T) and an encoder (last_hidden_state, B x T x H). Depending on the setup it returns token vectors B x T x H, which need pooling, or sentence vectors B x H.

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.

The feature extraction checklist: input is a sentence or document, the target is that similar texts sit close, the prediction is one vector, the data is text pairs or query matches, training shapes the vector space, inference encodes then stores or compares, and evaluation uses correlation or retrieval quality.

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.

Two sentence pairs through the same encoder. A man is slicing bread and Someone cuts a loaf get cosine similarity 0.91, a paraphrase pair. A man is slicing bread and A plane is landing get 0.12, an unrelated pair.

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.

Two panels: vectors u and v from the origin at 25 degrees apart with cosine 0.91, and at 85 degrees apart with cosine 0.09. Below, the formula cos(u, v) = (u dot v) / (norm u times norm v).

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.

Sentence A and sentence B go through one shared encoder and mean pooling, giving vector A and vector B, which feed a cosine similarity of 0.76.

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.0400

The 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.

A similar pair, The cat sat on the mat and A cat is sitting on a mat, gets cosine 0.86 against target 1.0 and loss 0.02. An unrelated pair, The capital of France is Paris and Bananas grow on plants, gets cosine -0.27 against target 0.0 and loss 0.07. The loss is (s - y) squared, mean squared error.

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.85

The 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.

A cosine score axis from 0 to 1 with a threshold marker at 0.85. Scores below it mean not duplicate and scores at or above it mean duplicate, with a note that a higher threshold gives fewer false matches.

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:

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.0

The 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.

A scatter of human score against model score, then two panels: Pearson, which measures the linear relationship of the scores, and Spearman, which measures the monotonic relationship of their ranks, both ranging from -1.0 to 1.0.

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.

The sentence similarity checklist: the input is two texts, the target is a 0 to 5 score, the prediction is two vectors and their cosine, the data is labeled pairs, training pulls pairs close or pushes them apart, inference applies a threshold, and evaluation uses correlation or F1.

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.

Two input sentences, a man is slicing bread and someone cuts a loaf, go through a sentence embedding model into two output vectors, which give a cosine score of 0.91. Encode, compare, decide.

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:

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.