Sub topic 2
Cosine similarity and why embeddings are normalized
This chapter assumes you know Python and PyTorch tensor operations, the dot product, and the vector norm. It also assumes you know what an embedding is from the previous chapter. By the end you should be able to compute cosine similarity by hand, explain why CLIP normalizes its embeddings, and avoid the common mistakes that come from forgetting to.
Comparing vectors: dot product and its problem
An embedding is a vector, so comparing two items means comparing two vectors. The simplest comparison is the dot product:
a · b = Σ aᵢ bᵢ
The dot product is large when two vectors point the same way and also when either vector is long. That second effect is a problem. Suppose an image embedding has a large norm because of some quirk of the image, such as high contrast or a lot of texture. Its dot product with every text embedding will tend to be large too. The score then reflects the vector's length, not how well the image matches the caption.
The geometric form of the dot product shows the two ingredients:
a · b = ‖a‖ ‖b‖ cos θ
Here ‖a‖ is the length (L2 norm) of a, and θ is the angle between the vectors. Length and direction are mixed together. For matching, we want only the direction.
Cosine similarity
Cosine similarity removes the length by dividing it out:
cos(a, b) = (a · b) / (‖a‖ ‖b‖)
The result lies between -1 and 1:
| Value | Meaning |
|---|---|
| 1 | Same direction (angle 0°) |
| 0 | Orthogonal (angle 90°), no relationship |
| -1 | Opposite direction (angle 180°) |
Scaling a vector by any positive number does not change its cosine similarity with anything. cos(3a, b) equals cos(a, b).
import torch
import torch.nn.functional as F
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([2.0, 4.0, 6.0]) # same direction as a, twice as long
c = torch.tensor([-1.0, 0.5, 0.0])
def cosine(x, y):
return (x @ y) / (x.norm() * y.norm())
print("dot(a, b):", (a @ b).item()) # 28.0, inflated by length
print("cos(a, b):", cosine(a, b).item()) # 1.0, same direction
print("cos(a, c):", cosine(a, c).item()) # small, nearly orthogonal
print("builtin :", F.cosine_similarity(a, b, dim=0).item())The vector b is just a stretched, so the cosine is 1 even though the dot product is 28. That is the behavior we want when asking "do these two things mean the same?"
Normalization turns cosine into a dot product
If you rescale every embedding to length 1 first, the denominator disappears:
â = a / ‖a‖, so cos(a, b) = â · b̂
This is why CLIP code calls F.normalize(x, dim=-1) and then uses a plain matrix multiplication. After normalization, every embedding lies on the surface of a unit hypersphere. Cosine similarity for a whole batch becomes one matrix product, which GPUs handle very efficiently.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
image_emb = torch.randn(4, 512) # 4 images
text_emb = torch.randn(5, 512) # 5 captions
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
print(image_emb.norm(dim=-1)) # all 1.0 (up to float error)
sim = image_emb @ text_emb.t() # shape (4, 5), every entry is a cosine
print(sim.shape, sim.min().item() >= -1.0, sim.max().item() <= 1.0)Each row of sim holds one image's cosine similarity to every caption. This (images, texts) matrix is the central object in CLIP training and inference.
Why CLIP normalizes
Normalization does several jobs in CLIP.
- The score depends on direction only. The two encoders are different networks and produce vectors with different natural scales. Normalizing puts them on equal footing, so the image-text score is not biased by whichever encoder outputs larger numbers.
- The score has a fixed range. Logits in the contrastive loss would otherwise be unbounded. A network could lower the loss just by inflating vector norms, which changes nothing about meaning. Normalization removes that shortcut. The model has to arrange directions to get matches right.
- Scale becomes an explicit, learned knob. Because cosines are confined to [-1, 1], the softmax over them would be very flat (all probabilities close to equal). CLIP multiplies the cosines by a learned scalar, the logit scale, to sharpen them. A later chapter covers it. The key point here is that normalization separates "which direction" from "how confident", and the temperature handles the second part.
- Retrieval becomes simple. With unit vectors, ranking by cosine, ranking by dot product, and ranking by smallest Euclidean distance all give the same order. That lets you use fast dot-product search libraries on stored embeddings.
The last point follows from a short identity. For unit vectors, ‖â − b̂‖² = 2 − 2 (â · b̂). A larger dot product means a smaller distance.
Worked example: one image, three captions
Take 2-dimensional vectors so we can compute by hand. Let the image embedding be i = (3, 4), and the captions be t1 = (6, 8), t2 = (0, 5), t3 = (-4, -3).
- ‖i‖ = 5, so î = (0.6, 0.8).
- t1 has norm 10, so t̂1 = (0.6, 0.8). Cosine = 0.36 + 0.64 = 1.0.
- t2 has norm 5, so t̂2 = (0, 1). Cosine = 0.8.
- t3 has norm 5, so t̂3 = (−0.8, −0.6). Cosine = −0.48 − 0.48 = −0.96.
Raw dot products would be 50, 20, and −24. The ranking is the same here, but the raw values depend on the lengths. If t2 were scaled to (0, 50), its dot product would be 200 and it would beat t1 even though its direction is worse. Cosine similarity is immune to that.
Edge cases and common errors
- Forgetting to normalize at inference.
get_image_featuresandget_text_featuresin Hugging Face return unnormalized projections. If you compare them with a plain dot product, scores will be skewed by norm. CallF.normalizefirst, or useF.cosine_similarity. - Normalizing along the wrong dimension. For a
(batch, dim)tensor, usedim=-1(ordim=1). Usingdim=0normalizes each feature column across the batch, which is wrong and silently runs without error. - Zero vectors. A zero vector has no direction, and dividing by its norm gives NaN.
F.normalizeguards this with a small epsilon (default1e-12), so it returns zeros. A hand-written division does not. - Reading cosine values as probabilities. CLIP cosines for matching pairs are often only around 0.2 to 0.35, not near 1. Image and text embeddings do not overlap perfectly, a known effect called the modality gap. Compare scores relatively (which caption is higher), not against a fixed threshold, unless you have calibrated one on your own data.
- Mixing normalized and unnormalized stores. If a vector database holds unit vectors, the query must be normalized too. Otherwise the ranking is still correct for a fixed query, but any score thresholds you set are meaningless.
- Half precision. In float16, computing a norm of a long vector can overflow or lose precision. Normalize in float32 if you see NaN values.
import torch
import torch.nn.functional as F
x = torch.randn(8, 512)
wrong = F.normalize(x, dim=0) # normalizes across the batch, not per sample
right = F.normalize(x, dim=-1) # normalizes each row
print(wrong.norm(dim=-1)[:3]) # not 1
print(right.norm(dim=-1)[:3]) # 1Summary of the working model
Cosine similarity compares direction and ignores length. Normalizing both embeddings to unit length makes cosine equal to a dot product, so one matrix multiplication scores every image against every caption. CLIP then applies a learned scale to those bounded scores before the softmax. The next chapters build on this similarity matrix to define the joint embedding space and the contrastive loss.
Exercise
The image embedding is i = (1, 1) and the caption embeddings are t1 = (2, 0) and t2 = (0, 10). Compute the cosine similarity of i with each caption. Which caption ranks first by cosine, and which ranks first by raw dot product? Why do they differ?
Show answer
‖i‖ = √2, ‖t1‖ = 2, ‖t2‖ = 10. The dot products are i·t1 = 2 and i·t2 = 10. Cosines are 2 / (√2 · 2) ≈ 0.707 for t1 and 10 / (√2 · 10) ≈ 0.707 for t2. By cosine the two captions tie, since both are 45° from i. By raw dot product t2 ranks first, because its vector is five times longer than t1. The dot product mixes in length, while cosine measures only direction.
Exercise
Write a function batch_cosine(a, b) that takes tensors of shape (n, d) and (m, d) and returns an (n, m) matrix of cosine similarities using only F.normalize and a matrix multiplication. What happens if you pass in a row of all zeros?
Show answer
def batch_cosine(a, b): return F.normalize(a, dim=-1) @ F.normalize(b, dim=-1).t(). A zero row stays all zeros after F.normalize, because it divides by max(norm, eps) with eps = 1e-12. Its similarity to every row of the other tensor is therefore 0, and no NaN appears. A manual a / a.norm() would produce NaN.
Exercise
Give two reasons CLIP normalizes embeddings before computing the logits, and explain why a learned scale is then needed.
Show answer
First, normalization makes the score depend only on direction, so differences in norm between the image and text encoders cannot bias matching, and the model cannot lower the loss by inflating vector lengths. Second, it bounds the scores to [-1, 1] and makes cosine equal to a dot product, so a whole batch is scored with one matrix multiplication. A softmax over values confined to [-1, 1] is nearly flat, so a learned scale (the logit scale, the inverse of the temperature) multiplies the cosines to make the distribution sharp enough to train on.