How to Measure the Cosine Similarity of Two Tensors in PyTorch
Cosine similarity measures how closely two vectors point in the same direction, whatever their length: 1 when they point the same way, 0 when they're at a right angle, and -1 when they point in opposite directions. It's how embeddings, the vectors models use for meaning, are compared. PyTorch computes it with cosine_similarity. This guide measures it on three tiny vectors in PyTorch 2.15.0.
Syntax
from torch.nn.functional import cosine_similarity
similarity = cosine_similarity(<x1>, <x2>, dim=1)
| Part | What it means |
|---|---|
<x1>, <x2> | The two tensors to compare, of the same shape or shapes that broadcast to one |
dim | Optional. The dimension that holds each vector's numbers; 1 if you leave it out. The result has one number for each vector along the other dimensions |
PyTorch's reference says it "Returns cosine similarity between x1 and x2, computed along dim." It divides the dot product of the two vectors by the product of their lengths.
The Example
Three vectors of two numbers each, written as one-row tables of shape [1, 2]: a points right, b points right and up at 45 degrees, c points left. The script compares a with itself, with b and with c, then compares two flat vectors of shape [2] with dim=0.
Prerequisites
- A uv project with PyTorch and NumPy.
uv add torch numpyadds both; without NumPy, PyTorch 2.15.0 prints a warning each time it starts. This guide uses PyTorch 2.15.0 and NumPy 2.5.5 on Python 3.15.2, with uv 0.13.10, on an Apple M1 Pro.
Step 1: Write the Script
import torch
from torch.nn.functional import cosine_similarity
a = torch.tensor([[1.0, 0.0]])
b = torch.tensor([[1.0, 1.0]])
c = torch.tensor([[-1.0, 0.0]])
print(cosine_similarity(a, a))
print(cosine_similarity(a, b))
print(cosine_similarity(a, c))
print(cosine_similarity(torch.tensor([1.0, 0.0]), torch.tensor([1.0, 1.0]), dim=0))

Step 2: Run It
uv run python cosine.py
tensor([1.])
tensor([0.7071])
tensor([-1.])
tensor(0.7071)
![The terminal after uv run python cosine.py: tensor([1.]), tensor([0.7071]), tensor([-1.]) and tensor(0.7071).](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-cosine-02-output.webp)
awith itself:1, the same direction.awithb:0.7071, the cosine of 45 degrees. The vectors point partly the same way.awithc:-1, opposite directions.- The flat vectors with
dim=0:0.7071again, as a single number, since there was only one pair to compare.
The one-row inputs gave a result with one number per row, shape [1]: the function compares the vectors row by row along dim=1 and removes that dimension. The command works unchanged in PowerShell.
Compare Many Pairs at Once
With tables of several rows, cosine_similarity compares row 1 with row 1, row 2 with row 2, and so on, and returns one number per row: two tables of 100 random vectors of shape [100, 384] gave a result of shape [100]. To compare one vector against many, make it a single row and PyTorch's broadcasting compares it with every row of the other tensor: a from the script against a table holding a, b and c printed tensor([ 1.0000, 0.7071, -1.0000]).
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Comparing two flat vectors without dim=0 | IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1): see the fix | Pass dim=0, or make each vector a row of shape [1, n] |
Using tensors of whole numbers, such as torch.tensor([[1, 0]]) | RuntimeError: expected common dtype to be floating point, yet common dtype is Long: see the fix | Write the numbers with .0, or convert with .float() |
Reading 0.7071 as "70% the same" | It's the cosine of an angle, not a percentage | Compare scores with each other: higher is more similar |
FAQ
Is cosine similarity the same as distance?
No. Distance depends on the vectors' lengths, cosine similarity only on their directions. For [1, 0] and [5, 0], cosine_similarity printed tensor([1.]) while torch.dist, the distance between them, printed tensor(4.).
What does a similarity of 0 mean?
The vectors are at a right angle: neither points towards nor away from the other. For embeddings, it usually means unrelated.
Conclusion
cosine_similarity gave 1 for a vector with itself, 0.7071 for vectors 45 degrees apart and -1 for opposite vectors, row by row along dim=1, and dim=0 compared two flat vectors directly.
Additional Resources
- torch.nn.functional.cosine_similarity — PyTorch's reference, with the formula,
dimandeps. - torch.nn.CosineSimilarity — the same calculation as a module.
