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
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
print(siglip_loss([[1.0, 0.0], [0.0, 1.0]], 1.0, 0.0))
1.0064
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
+1on the diagonal,-1elsewhere. - Sum over all
N*Npairs but divide byN. - Use a numerically stable
log_sigmoid; round to 4 decimals.