I'll derive the gradient of the InfoNCE loss and explain how it encourages positive pairs to be closer in embedding space.
InfoNCE Loss Setup
The InfoNCE loss for a query sample with representation zq, a positive sample z+, and K negative samples {zi}i=1K is:
L=−logexp(
where τ is the temperature parameter.
Gradient Derivation
Let me define similarity scores: s+=zq⋅z+ and
The loss can be rewritten as:
L=−s++log(∑
Gradient w.r.t. query representation zq:
∂zq
Computing each term:
- ∂zq∂s+
where pj=∑k is the softmax probability.
Therefore:
∂zq∂L
Gradient w.r.t. positive representation z+:
∂z+∂L=−
Gradient w.r.t. negative representation zi:
∂zi∂L=
Why This Encourages Positive Pairs to Be Closer
The gradients reveal the learning dynamics:
-
For the query zq: The gradient update (negative of gradient) pushes it:
- Toward the positive sample z+ with strength (
The key insights are:
-
Adaptive weighting: The softmax probabilities pj act as adaptive weights. Hard negatives (those with high similarity to the query) get larger pi values, so they're pushed away more strongly.
-
Symmetric attraction: Both query and positive representations are pulled toward each other, creating a symmetric attraction force proportional to . When they're already close (), the attraction weakens.
This gradient structure ensures that in embedding space, semantically similar (positive) pairs cluster together while dissimilar (negative) pairs are pushed apart, creating well-separated representations that capture semantic structure.