Symmetric CLIP Loss with a Learnable Temperature
Problem Statement
The full CLIP loss is the average of two cross-entropy terms — image-to-text and text-to-image — over the scaled similarity matrix. Implement it from a matrix of cosine similarities and a learnable temperature.
Background
Given cosine similarities sim (N x N, row = image, col = text), CLIP scales them by a temperature and treats each row (and each column) as an N-way classification whose correct label is the diagonal:
with targets 0..N-1. Cross-entropy of a row is -log softmax(row)[label]. In practice 1/tau is a learned "logit scale" clamped to at most 100; here you are given tau directly. Use a numerically stable log-softmax (subtract the max).
Your Task
Implement:
def clip_loss(sim, tau):
Return the scalar loss rounded to 4 decimals.
Input Format
- sim: N x N nested list of cosine similarities.
- tau (float): temperature, tau > 0.
Output Format
- A float rounded to 4 decimals.
Sample
print(clip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0))
Output:
0.3133
Example
print(clip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0))
0.3133
Each row's logits are [1,0] or [0,1]; the CE of the correct class is -log(softmax)[label] = 0.3133, symmetric for columns, so the average is 0.3133.
Constraints
1 <= N <= 512,tau > 0.- Average the row-wise and column-wise cross-entropies.
- Diagonal entries are the correct labels.
- Use a stable log-softmax; round the final scalar to 4 decimals.