How to Measure How Similar Two Sentences Are with Hugging Face Embeddings
"A man is playing a guitar" and "Someone is making music" share only the word "is", yet they mean nearly the same thing. Comparing their embeddings, the lists of numbers a model gives each sentence, captures that: the closer the meanings, the closer the numbers. This guide scores one sentence against three others with a Hugging Face feature-extraction pipeline and cosine similarity, with Transformers 5.26.0 on Python 3.14.
Syntax
from torch.nn.functional import cosine_similarity
similarity = cosine_similarity(<embedding_a>, <embedding_b>)
| Part | What it means |
|---|---|
<embedding_a>, <embedding_b> | The two sentences' embeddings, each a tensor of shape [1, vector size] from the same model |
cosine_similarity(…) | Compares the directions of the two vectors: close to 1 when they point the same way, around 0 when they're unrelated, below 0 when they point apart |
similarity | A tensor with one number; similarity.item() turns it into a Python float |
The embeddings come from a feature-extraction pipeline, averaged over the tokens, as How to Turn a Sentence into an Embedding with a Hugging Face Feature-Extraction Pipeline explains. How to Measure the Cosine Similarity of Two Tensors in PyTorch shows what the function computes, with two-number vectors.
The Example
One sentence, "A man is playing a guitar.", compared with three others: one close in meaning, one about a different everyday activity, one about something else entirely. The model is sentence-transformers/all-MiniLM-L6-v2, a small model trained so that sentences with similar meanings get similar embeddings. It's Apache-2.0 licensed.
Prerequisites
- uv. This guide uses uv 0.13.10. The project uses Python 3.14, which uv downloads if needed.
- About 91 MB for the model, downloaded on the first run.
Step 1: Create the Project
uv init --python 3.14 similarity-demo
cd similarity-demo
uv add transformers torch
That's a project with Transformers 5.26.0 and PyTorch 2.15.0.
Step 2: Write the Script
from torch.nn.functional import cosine_similarity
from transformers import pipeline
extractor = pipeline(
"feature-extraction",
model="sentence-transformers/all-MiniLM-L6-v2",
revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
)
def embed(text):
return extractor(text, return_tensors=True).mean(dim=1)
anchor = embed("A man is playing a guitar.")
for other in [
"Someone is making music.",
"A woman is slicing an onion.",
"The stock market fell today.",
]:
similarity = cosine_similarity(anchor, embed(other))
print(f"{similarity.item():.3f} {other}")

embed turns a text into one vector of 384 numbers. The first sentence is embedded once, as anchor; the loop embeds each other sentence and prints its similarity with the anchor, rounded to three decimals.
Step 3: Run It
uv run python similarity.py
Loading weights: 100%|██████████████████████████████████████████| 103/103 [00:00<00:00, 9415.95it/s]
0.579 Someone is making music.
0.089 A woman is slicing an onion.
-0.050 The stock market fell today.

The scores follow the meanings:
- 0.579 for "Someone is making music.", the same scene in other words.
- 0.089 for "A woman is slicing an onion.", a person doing something else.
- -0.050 for "The stock market fell today.", nothing in common at all.
The numbers mean little on their own: what counts is their order. To find the closest sentence, compare against many and take the highest. On the first run, download progress bars for the model's files come before these lines. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Comparing embeddings from two different models | The numbers mean different things, so the score is meaningless | Embed every sentence with the same model |
| Comparing the token tensors directly | Sentences of different lengths give different shapes, such as [1, 9, 384] and [1, 7, 384] here, which can't be compared one-to-one | Average each into [1, 384] first |
| Using a model not trained for embeddings | Every pair can score high, so the scores can't tell sentences apart | Use a model made for sentence embeddings |
| Expecting a fixed threshold to mean "same meaning" | Scores vary by model and by kind of text | Choose a threshold from examples of your own texts |
FAQ
Why cosine similarity and not plain distance?
Cosine similarity compares directions and ignores length, which suits embeddings: the meaning is in which way the vector points. It's also what this model was trained with: its card says that during training "we compute the cosine similarity from each possible sentence pairs from the batch."
How do I compare many sentences at once?
Embed them all, then compare: cosine_similarity works on a whole batch of vectors at once, row by row. For large collections, a vector database does it for you.
Is this what semantic search does?
Yes, at its core: embed the documents once, embed each query, and return the documents with the highest similarity to it.
Conclusion
Embedding each sentence with all-MiniLM-L6-v2 and comparing them with cosine_similarity scored "Someone is making music." at 0.579 against "A man is playing a guitar.", far above the onion (0.089) and the stock market (-0.050): the order of the scores matches the order of the meanings.
Additional Resources
- torch.nn.functional.cosine_similarity — the function and its
dimargument. - FeatureExtractionPipeline — the pipeline that makes the embeddings.
- sentence-transformers/all-MiniLM-L6-v2 — the model's card.
