PIXELBANKv9.1.0
Menu

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:

logits=simτ,L=12(CErows+CEcols)\text{logits} = \frac{\text{sim}}{\tau}, \qquad \mathcal{L} = \tfrac{1}{2}\big(\text{CE}_{\text{rows}} + \text{CE}_{\text{cols}}\big)

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:

Input:
print(clip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0))
Output:
0.3133
Reasoning:

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.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Symmetric CLIP Loss with a Learnable Temperature - Medium | PixelBank