PIXELBANKv9.1.0
Menu

SigLIP Loss with the Learnable Bias

Problem Statement

SigLIP replaces CLIP's softmax with an independent binary sigmoid loss per image-text pair, adding a learnable temperature t and bias b that correct for the extreme positive/negative imbalance. Implement it.

Background

For a batch of N pairs with cosine similarities sim (N x N), define the label matrix z_{ij} = +1 on the diagonal (matches) and z_{ij} = -1 off it (all other pairs are negatives). The SigLIP loss is

L=−1N∑i∑jlog⁡σ ⁣(zij (t⋅simij+b))\mathcal{L} = -\frac{1}{N}\sum_{i}\sum_{j} \log \sigma\!\big(z_{ij}\,(t\cdot \text{sim}_{ij} + b)\big)

Note the normalization is by N (the batch size), not N^2. The bias b is initialized very negative (about -10) so training starts near the correct all-negative prior. Use log_sigmoid(x) = -softplus(-x) for stability.

Your Task

Implement:

def siglip_loss(sim, t, b):

Return the scalar loss rounded to 4 decimals.

Input Format

  • sim: N x N nested list of cosine similarities.
  • t (float): temperature/scale.
  • b (float): bias.

Output Format

  • A float rounded to 4 decimals.

Sample

print(siglip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0, 0.0))

Output:

1.0064

Example:

Input:
print(siglip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0, 0.0))
Output:
1.0064
Reasoning:

Logits t*sim+b are [[1,0],[0,1]]; with signs [[+,-],[-,+]] the diagonal terms use -log-sigmoid(1)=0.3133 and the off-diagonals -log-sigmoid(0)=0.6931. The four values sum to 2.0128; divided by N=2 gives 1.0064.

Constraints:

  • 1 <= N <= 512.
  • Labels are +1 on the diagonal, -1 elsewhere.
  • Sum over all N*N pairs but divide by N.
  • Use a numerically stable log_sigmoid; round 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.
SigLIP Loss with the Learnable Bias - Medium | PixelBank