Sub topic 10
The learned temperature (logit scale)
This chapter assumes you know the dot product, vector norms, softmax, and cross-entropy loss, and that you have read the chapters on cosine similarity and the symmetric contrastive loss. Here we look at one scalar inside the CLIP loss, the temperature, and why it matters.
The problem: cosine similarities are too small
After both embeddings are normalized to unit length, the dot product of an image and a text embedding is a cosine similarity. It lies in the range [-1, 1]. In practice, CLIP similarities for one image against a set of captions often sit in a narrow band, such as 0.18 to 0.32.
Softmax turns scores into probabilities. If you apply it directly to scores in a narrow band, the output is almost uniform. This is a numeric example with four candidate captions:
| Caption | Cosine similarity |
|---|---|
| matching caption | 0.32 |
| wrong caption A | 0.25 |
| wrong caption B | 0.22 |
| wrong caption C | 0.20 |
Softmax of these raw values gives the right caption about 28% probability, against 26%, 25% and 24% for the others. The cross-entropy loss stays near log 4 ≈ 1.39 even when the ranking is perfect. The gradients are small and nearly identical for every pair, so the model gets a weak signal about which pairs to separate.
Multiplying the scores by a constant larger than 1 before the softmax fixes this. That constant is the logit scale, and it is the inverse of the temperature.
Temperature and logit scale
A temperature τ divides the similarities before the softmax:
logit_ij = cos(image_i, text_j) / τEquivalently, with a logit scale s = 1/τ:
logit_ij = s * cos(image_i, text_j)A small τ (large s) sharpens the distribution. A large τ (small s) flattens it. The final CLIP-style loss uses these scaled logits in both cross-entropy directions, as in the loss chapter.
The effect on the example above, using s = 1, 10 and 100:
import torch
sims = torch.tensor([0.32, 0.25, 0.22, 0.20])
for s in [1, 10, 100]:
print(s, torch.softmax(s * sims, dim=0).tolist())At s = 1 the probabilities are close to uniform. At s = 10 the right caption gets about 0.40. At s = 100 it gets about 0.99, and the loss on this example is almost zero.
What the temperature does to the gradient
The temperature also controls how much the loss cares about hard negatives, which are wrong pairs with high similarity.
- With a high temperature (small s), the softmax is flat. Every negative gets a similar weight, so the loss treats easy and hard negatives alike.
- With a low temperature (large s), the softmax concentrates on the highest-scoring wrong pairs. The gradient pushes hardest against those hard negatives.
- If s is too large, the model sees large losses from a few confusing pairs and can become unstable. Noisy or mislabeled pairs get large gradients too, because web captions are often a loose description of the image.
So the temperature trades off signal strength against sensitivity to hard and noisy examples. Setting it by hand needs a sweep, and the best value changes with batch size and data.
Learning the logit scale
CLIP avoids a manual sweep by making the temperature a trained parameter. The model stores a scalar logit_scale and trains it by gradient descent with the rest of the weights.
Two design choices matter:
- Log parameterization. The parameter holds log(s), and the loss uses
logit_scale.exp(). This keeps s positive and lets gradient steps change it multiplicatively. This is why the loss code calls.exp(). - Initialization and clipping. The original CLIP initializes the temperature at τ = 0.07, so s ≈ 14.3 and the stored value is log(1/0.07) ≈ 2.659. It clamps the scale so that it never exceeds 100, which means the stored value never exceeds log(100) ≈ 4.605. Without the clamp, the temperature can shrink without bound and training becomes unstable.
The following module shows how the scale sits in a model and how to clamp it:
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ClipHead(nn.Module):
def __init__(self, init_temperature=0.07, max_scale=100.0):
super().__init__()
self.logit_scale = nn.Parameter(torch.tensor(math.log(1 / init_temperature)))
self.max_log_scale = math.log(max_scale)
def forward(self, image_emb, text_emb):
image_emb = F.normalize(image_emb, dim=-1)
text_emb = F.normalize(text_emb, dim=-1)
logits = self.logit_scale.exp() * image_emb @ text_emb.t()
labels = torch.arange(logits.size(0), device=logits.device)
loss = (F.cross_entropy(logits, labels) + F.cross_entropy(logits.t(), labels)) / 2
return loss
@torch.no_grad()
def clamp_scale(self):
self.logit_scale.clamp_(0, self.max_log_scale)
head = ClipHead()
opt = torch.optim.AdamW(head.parameters(), lr=1e-3)
image_emb = torch.randn(8, 32, requires_grad=True)
text_emb = torch.randn(8, 32, requires_grad=True)
loss = head(image_emb, text_emb)
loss.backward()
opt.step()
head.clamp_scale() # call after every optimizer step
print(loss.item(), head.logit_scale.exp().item())Call clamp_scale() after each optimizer step. In a real training loop, you usually also exclude this parameter from weight decay, because decay would pull the log scale toward zero (s = 1) and fight the learning signal.
How the scale changes during training
The scale generally rises as training goes on. Early in training, embeddings are not yet well separated, so a moderate scale is enough. As matching and non-matching pairs separate, the model gains from a sharper softmax, so the loss gradient on the scale pushes it up until it reaches the clamp or a balance point. For the released OpenAI CLIP models the final scale is 100, which is the clamp value.
The temperature at inference
The scale is part of the trained checkpoint, and you use it at inference. In the zero-shot example from the earlier chapter, the Hugging Face model returns logits_per_image, which is already multiplied by exp(logit_scale). That is why a softmax over those logits gives sharp, usable probabilities.
from transformers import CLIPModel
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
print(model.logit_scale.item()) # log scale, about 4.6052
print(model.logit_scale.exp().item()) # about 100Note how this affects your code:
- Class probabilities depend on the scale. If you compute cosine similarities yourself and apply softmax without the scale, you get nearly uniform probabilities, even though the argmax is unchanged.
- Ranking does not depend on the scale. Scaling by a positive constant keeps the order of scores. For retrieval, you can rank by raw cosine similarity and ignore the scale.
- Calibration is not guaranteed. A softmax output of 0.99 does not mean the label is right 99% of the time. The scale was tuned for the training loss, not for calibrated confidence. If you need calibrated probabilities, fit a separate temperature on a validation set.
Common errors
- Forgetting
.exp(). Using the stored log value directly as the multiplier gives a scale of about 4.6 instead of 100, so the loss barely trains. - Applying the scale before normalization. The scale multiplies cosine similarities. If the embeddings are not normalized, the logits are unbounded and the scale loses its meaning.
- No clamp. The scale can grow without bound, which gives very large logits, overflow in half precision, and unstable loss.
- Weight decay on the scale. Decay pulls the parameter to zero and works against learning.
- Treating the scale as a fixed constant when comparing models. SigLIP uses a learned temperature and also a learned bias with a different loss, so values are not interchangeable between model families.
Summary
- Normalized embeddings produce similarities in a narrow range, so a softmax on them is nearly uniform.
- The logit scale s = 1/τ multiplies the similarities, sharpening the softmax and strengthening the gradient.
- Low temperature emphasizes hard negatives and also noisy pairs. High temperature treats all negatives alike.
- CLIP learns log(s) as a parameter, initializes τ at 0.07, and clamps s at 100.
- At inference, the scale shapes probabilities but not rankings.
Exercise
A CLIP-style model has a stored logit_scale parameter of 3.0. For one image, the cosine similarities to three captions are 0.30, 0.20 and 0.10. (a) What multiplier is applied to the similarities? (b) Which caption has the highest probability, and would it change if the scale were 4.6 instead? (c) Why is clamping needed during training?
Show answer
(a) The multiplier is exp(3.0), about 20.1, so the logits are about 6.03, 4.02 and 2.01. (b) The first caption (0.30) has the highest probability, about 0.867. With the scale at 4.6, the multiplier is about 99.5 and the first caption's probability rises to nearly 1, but the ranking stays the same because scaling by a positive constant preserves order. (c) Without a clamp, the scale can keep growing, which creates very large logits, overflow in low precision, and unstable gradients. The clamp at 100 prevents this.
Exercise
Write a short PyTorch snippet that computes the softmax probabilities for similarities sims = torch.tensor([0.28, 0.24, 0.21]) at scales 1, 14.3 and 100, and say what trend you expect in the probability of the first entry.
Show answer
Code: import torch sims = torch.tensor([0.28, 0.24, 0.21]) for s in [1, 14.3, 100]: print(s, torch.softmax(s * sims, dim=0)[0].item()) The probability of the first entry increases as the scale rises, from about 0.35 at s = 1 toward 1.0 at s = 100, because a larger scale sharpens the softmax around the largest similarity.