Practice / Backprop by hand

Contrastive loss and the InfoNCE gradient

Ten problems on contrastive learning: InfoNCE as a softmax cross-entropy over similarities, the gradient of cosine similarity, the gradient with respect to the anchor and to the positive and negative candidates, what the temperature does to the weighting of negatives, the symmetric CLIP-style batch loss and its logit-matrix gradient, scale invariance of the normalised loss, the gradient with respect to a learned temperature, the matrix form through the normalisation, and why unnormalised dot-product logits are not scale invariant, with worked solutions and the mistakes that drop the projection, the 1/τ, the column loss or the sign of the temperature gradient.

Before you start

A contrastive loss asks an encoder to place an anchor close to its positive and far from a set of negatives, and InfoNCE, the loss behind SimCLR, MoCo and CLIP, does it with a softmax over similarities: it is cross-entropy with the positive as the label. So its gradient with respect to the logits is the softmax page's p−yp - y, and everything else on this page is the chain rule through two things that page did not have: a cosine similarity, which normalises both vectors, and a temperature. These ten problems compute the gradient of the cosine, push p−yp - y through it to the anchor and to each candidate, read off what the temperature does to the weights on hard and easy negatives, do the symmetric two-direction batch loss used by CLIP, differentiate with respect to a learned temperature, and show why the normalisation is what stops the encoder from cheating by scaling. The five mistakes each leave a working training run: a cosine gradient that forgets the norm, a dropped 1/τ1/\tau, a one-directional batch loss, a normalisation backward without its projection, and a temperature gradient with the wrong sign.

  • Vectors are columns and gradients have the shape of their variable, as on the earlier pages. u^=u/∥u∥\hat u = u/\|u\| is the unit vector along uu, and II is the identity.
  • The anchor is u∈Rdu \in \mathbb{R}^d and the candidates are v1,…,vK∈Rdv_1, \dots, v_K \in \mathbb{R}^d; candidate 11 is the positive and the rest are negatives. y=e1y = e_1 is the one-hot label.
  • Cosine similarity is c(u,v)=u⊤v∥u∥∥v∥=u^⊤v^c(u, v) = \dfrac{u^\top v}{\|u\|\|v\|} = \hat u^\top\hat v, and cj=c(u,vj)c_j = c(u, v_j).
  • The temperature τ>0\tau > 0 turns similarities into logits zj=cj/τz_j = c_j/\tau; p=softmax⁡(z)p = \operatorname{softmax}(z), so pj=ezj/∑kezkp_j = e^{z_j}/\sum_k e^{z_k}, and ∑jpj=1\sum_j p_j = 1.
  • InfoNCE for one anchor is ℓ=−log⁡p1=−z1+log⁡∑jezj\ell = -\log p_1 = -z_1 + \log\sum_j e^{z_j}. The softmax page showed ∇z(−log⁡p1)=p−y\nabla_z(-\log p_1) = p - y (its Problem 5) and that softmax⁡(z/T)\operatorname{softmax}(z/T) sharpens as T→0T \to 0 (its Problem 9).
  • The Jacobians page's Problem 9 gives ∂u^/∂u=1∥u∥(I−u^u^⊤)\partial\hat u/\partial u = \dfrac{1}{\|u\|}(I - \hat u\hat u^\top), and the matrix-calculus page gives ∇u∥u∥=u^\nabla_u\|u\| = \hat u and ∇u(a⊤u)=a\nabla_u(a^\top u) = a.
  • Batch form: NN pairs (ui,vi)(u_i, v_i), with U^\hat U and V^\hat V the N×dN\times d matrices of unit rows and Z=U^V^⊤/τZ = \hat U\hat V^\top/\tau the N×NN\times N logit matrix, Zij=c(ui,vj)/τZ_{ij} = c(u_i, v_j)/\tau. PrP_r is the row-wise softmax of ZZ and PcP_c the column-wise softmax.

Builds on: The softmax Jacobian, Jacobians and the chain rule

Problems

  1. ·

    Show that ℓ=−z1+log⁡∑jezj\ell = -z_1 + \log\sum_j e^{z_j} equals −log⁡p1-\log p_1, compute ∇zℓ\nabla_z\ell, and deduce ∇cℓ\nabla_c\ell for the vector cc of similarities.

  2. ··

    Compute ∇uc(u,v)\nabla_uc(u, v) and ∇vc(u,v)\nabla_vc(u, v). Show that ∇uc\nabla_uc is orthogonal to uu and find its norm.

  3. ··

    Compute ∇uℓ\nabla_u\ell for InfoNCE with cosine similarities, and simplify it to an expression in u^\hat u, the unit candidates v^j\hat v_j, the weights pjp_j and the similarities cjc_j.

  4. ··

    Compute ∇vjℓ\nabla_{v_j}\ell for the positive (j=1j = 1) and for a negative (j≠1j \neq 1), and say in which direction each candidate moves under gradient descent.

  5. ··

    Show that the weight the loss puts on negative jj relative to negative kk is pj/pk=e(cj−ck)/τp_j/p_k = e^{(c_j - c_k)/\tau}. Describe pp and ∇cℓ\nabla_c\ell as τ→0\tau \to 0 and as τ→∞\tau \to \infty.

  6. ···

    The symmetric batch loss used by CLIP is L=12N∑i=1N[ℓirow+ℓicol]L = \dfrac1{2N}\sum_{i=1}^N\big[\ell^{\text{row}}_i + \ell^{\text{col}}_i\big] with ℓirow=−Zii+log⁡∑jeZij\ell^{\text{row}}_i = -Z_{ii} + \log\sum_je^{Z_{ij}} (anchor uiu_i against all vjv_j) and ℓicol=−Zii+log⁡∑jeZji\ell^{\text{col}}_i = -Z_{ii} + \log\sum_je^{Z_{ji}} (anchor viv_i against all uju_j). Compute ∇ZL\nabla_ZL.

  7. ··

    Show that ℓ\ell is unchanged by u→αuu \to \alpha u for any α>0\alpha > 0, that u⊤∇uℓ=0u^\top\nabla_u\ell = 0, and that ∇uℓ\nabla_u\ell evaluated at αu\alpha u is 1α\tfrac1\alpha times its value at uu. If u=Wxu = Wx for a projection WW and input xx, compute ∇Wℓ\nabla_W\ell.

  8. ···

    Compute ∂ℓ/∂τ\partial\ell/\partial\tau. CLIP learns the temperature through a logit scale s=1/τ=ets = 1/\tau = e^t with tt the trained parameter. Compute ∂ℓ/∂t\partial\ell/\partial t, and say which way tt moves when the positive's similarity exceeds the softmax-weighted average similarity.

  9. ···

    For the symmetric batch loss of Problem 6 with Z=U^V^⊤/τZ = \hat U\hat V^\top/\tau, compute ∇U^L\nabla_{\hat U}L and ∇V^L\nabla_{\hat V}L in matrix form, then ∇uiL\nabla_{u_i}L through the normalisation u^i=ui/∥ui∥\hat u_i = u_i/\|u_i\|.

  10. ··

    Suppose the logits were the plain dot products zj=u⊤vj/τz_j = u^\top v_j/\tau with no normalisation. Compute ∇uℓ\nabla_u\ell and u⊤∇uℓu^\top\nabla_u\ell, and show that when the positive has the largest logit the loss can be reduced by scaling uu up, without changing its direction.

Worked solutions

Problem 1

Show that ℓ=−z1+log⁡∑jezj\ell = -z_1 + \log\sum_j e^{z_j} equals −log⁡p1-\log p_1, compute ∇zℓ\nabla_z\ell, and deduce ∇cℓ\nabla_c\ell for the vector cc of similarities.

  1. −log⁡p1=−log⁡ez1∑jezj=−z1+log⁡∑jezj-\log p_1 = -\log\dfrac{e^{z_1}}{\sum_j e^{z_j}} = -z_1 + \log\sum_j e^{z_j}.log⁡(a/b)=log⁡a−log⁡b\log(a/b) = \log a - \log b and log⁡ez1=z1\log e^{z_1} = z_1.
  2. ∂ℓ/∂zj=−δj1+ezj∑kezk=pj−yj\partial\ell/\partial z_j = -\delta_{j1} + \dfrac{e^{z_j}}{\sum_k e^{z_k}} = p_j - y_j.The first term contributes only for j=1j = 1; the log-sum-exp has derivative pjp_j by the chain rule, ddzjlog⁡S=1S ∂S/∂zj\tfrac{d}{dz_j}\log S = \tfrac1S\,\partial S/\partial z_j with S=∑kezkS = \sum_k e^{z_k}. This is the softmax page's p−yp - y.
  3. z=c/τz = c/\tau, so ∂zj/∂cj=1/τ\partial z_j/\partial c_j = 1/\tau and ∇cℓ=1τ∇zℓ\nabla_c\ell = \tfrac1\tau\nabla_z\ell.Each cjc_j enters one logit, scaled by the constant 1/τ1/\tau.
  4. ℓ=−log⁡p1\ell = -\log p_1, ∇zℓ=p−y\nabla_z\ell = p - y, ∇cℓ=(p−y)/τ\nabla_c\ell = (p - y)/\tauEvery entry of ∇cℓ\nabla_c\ell is positive for a negative (pj>0p_j > 0) and negative for the positive (p1−1<0p_1 - 1 < 0): gradient descent raises the positive's similarity and lowers each negative's, in proportion to the softmax weight the loss currently gives it, divided by τ\tau. The rest of this page carries this vector through the similarities to the embeddings.

Problem 2

Compute ∇uc(u,v)\nabla_uc(u, v) and ∇vc(u,v)\nabla_vc(u, v). Show that ∇uc\nabla_uc is orthogonal to uu and find its norm.

  1. c=u^⊤v^c = \hat u^\top\hat v, and v^\hat v does not depend on uu.Definition of the cosine; vv is held fixed.
  2. ∇uc=(∂u^∂u)⊤v^=1∥u∥(I−u^u^⊤)v^\nabla_uc = \Big(\dfrac{\partial\hat u}{\partial u}\Big)^\top\hat v = \dfrac1{\|u\|}(I - \hat u\hat u^\top)\hat v.c=a⊤u^c = a^\top\hat u with a=v^a = \hat v constant, so ∇u^c=v^\nabla_{\hat u}c = \hat v and the chain rule through u^(u)\hat u(u) multiplies by the transposed Jacobian, which is symmetric (Before you start).
  3. (I−u^u^⊤)v^=v^−u^(u^⊤v^)=v^−c u^(I - \hat u\hat u^\top)\hat v = \hat v - \hat u(\hat u^\top\hat v) = \hat v - c\,\hat u.Distribute; u^⊤v^\hat u^\top\hat v is the scalar cc.
  4. By symmetry, ∇vc=1∥v∥(u^−c v^)\nabla_vc = \dfrac1{\|v\|}(\hat u - c\,\hat v).c(u,v)=c(v,u)c(u, v) = c(v, u), so swap the roles.
  5. u⊤∇uc=1∥u∥(u⊤v^−c u⊤u^)=1∥u∥(∥u∥c−c∥u∥)=0u^\top\nabla_uc = \dfrac{1}{\|u\|}\big(u^\top\hat v - c\,u^\top\hat u\big) = \dfrac1{\|u\|}\big(\|u\|c - c\|u\|\big) = 0.u⊤v^=∥u∥u^⊤v^=∥u∥cu^\top\hat v = \|u\|\hat u^\top\hat v = \|u\|c and u⊤u^=∥u∥u^\top\hat u = \|u\|.
  6. ∥∇uc∥2=1∥u∥2(v^⊤v^−2c u^⊤v^+c2u^⊤u^)=1−2c2+c2∥u∥2=1−c2∥u∥2\|\nabla_uc\|^2 = \dfrac{1}{\|u\|^2}\big(\hat v^\top\hat v - 2c\,\hat u^\top\hat v + c^2\hat u^\top\hat u\big) = \dfrac{1 - 2c^2 + c^2}{\|u\|^2} = \dfrac{1 - c^2}{\|u\|^2}.Expand ∥v^−cu^∥2\|\hat v - c\hat u\|^2 with unit vectors and u^⊤v^=c\hat u^\top\hat v = c.
  7. ∇uc=v^−c u^∥u∥\nabla_uc = \dfrac{\hat v - c\,\hat u}{\|u\|}, ∇vc=u^−c v^∥v∥\nabla_vc = \dfrac{\hat u - c\,\hat v}{\|v\|}; u⊤∇uc=0u^\top\nabla_uc = 0 and ∥∇uc∥=1−c2∥u∥\|\nabla_uc\| = \dfrac{\sqrt{1 - c^2}}{\|u\|}The gradient is the part of v^\hat v orthogonal to u^\hat u (the direction that turns uu towards vv), scaled by 1/∥u∥1/\|u\|: a long anchor turns more slowly. It vanishes when c=±1c = \pm1, where uu and vv are already aligned or opposed, and nothing in it can change the length of uu.

Problem 3

Compute ∇uℓ\nabla_u\ell for InfoNCE with cosine similarities, and simplify it to an expression in u^\hat u, the unit candidates v^j\hat v_j, the weights pjp_j and the similarities cjc_j.

  1. ∇uℓ=∑j∂ℓ∂cj∇ucj=1τ∑j(pj−yj) ∇ucj\nabla_u\ell = \sum_j\dfrac{\partial\ell}{\partial c_j}\nabla_uc_j = \dfrac1\tau\sum_j(p_j - y_j)\,\nabla_uc_j.ℓ\ell depends on uu only through the KK similarities; chain rule over all of them with Problem 1.
  2. =1τ∥u∥∑j(pj−yj)(v^j−cju^)= \dfrac{1}{\tau\|u\|}\sum_j(p_j - y_j)\big(\hat v_j - c_j\hat u\big).Problem 2 for each cjc_j; the common factor 1/∥u∥1/\|u\| comes out.
  3. ∑j(pj−yj)v^j=∑jpjv^j−v^1\sum_j(p_j - y_j)\hat v_j = \sum_jp_j\hat v_j - \hat v_1.yy is one-hot on the positive.
  4. ∑j(pj−yj)cju^=(∑jpjcj−c1)u^\sum_j(p_j - y_j)c_j\hat u = \Big(\sum_jp_jc_j - c_1\Big)\hat u.The same split; u^\hat u does not depend on jj.
  5. ∇uℓ=1τ∥u∥[∑jpjv^j−v^1−(∑jpjcj−c1)u^]\nabla_u\ell = \dfrac{1}{\tau\|u\|}\Big[\sum_jp_j\hat v_j - \hat v_1 - \Big(\sum_jp_jc_j - c_1\Big)\hat u\Big]The step −η∇uℓ-\eta\nabla_u\ell pulls uu towards the positive direction v^1\hat v_1 and pushes it away from the softmax-weighted average of all candidates, ∑jpjv^j\sum_jp_j\hat v_j, which is dominated by the negatives it currently confuses with the positive; the u^\hat u term removes whatever component of that lies along uu, so that u⊤∇uℓ=0u^\top\nabla_u\ell = 0 (Problem 7). The ∑j(pj−yj)=0\sum_j(p_j - y_j) = 0 identity does not kill the u^\hat u term, because each term carries its own cjc_j.

Problem 4

Compute ∇vjℓ\nabla_{v_j}\ell for the positive (j=1j = 1) and for a negative (j≠1j \neq 1), and say in which direction each candidate moves under gradient descent.

  1. ℓ\ell depends on vjv_j only through cjc_j.vjv_j appears in no other similarity.
  2. ∇vjℓ=∂ℓ∂cj∇vjcj=pj−yjτ⋅u^−cjv^j∥vj∥\nabla_{v_j}\ell = \dfrac{\partial\ell}{\partial c_j}\nabla_{v_j}c_j = \dfrac{p_j - y_j}{\tau}\cdot\dfrac{\hat u - c_j\hat v_j}{\|v_j\|}.Problem 1 for the first factor and Problem 2 (the ∇v\nabla_v form) for the second.
  3. Positive: ∇v1ℓ=p1−1τ∥v1∥(u^−c1v^1)\nabla_{v_1}\ell = \dfrac{p_1 - 1}{\tau\|v_1\|}(\hat u - c_1\hat v_1), with p1−1<0p_1 - 1 < 0.y1=1y_1 = 1 and 0<p1<10 < p_1 < 1.
  4. Negative: ∇vjℓ=pjτ∥vj∥(u^−cjv^j)\nabla_{v_j}\ell = \dfrac{p_j}{\tau\|v_j\|}(\hat u - c_j\hat v_j), with pj>0p_j > 0.yj=0y_j = 0.
  5. ∇vjℓ=pj−yjτ∥vj∥(u^−cjv^j)\nabla_{v_j}\ell = \dfrac{p_j - y_j}{\tau\|v_j\|}(\hat u - c_j\hat v_j): the positive moves along +(u^−c1v^1)+(\hat u - c_1\hat v_1), towards the anchor's direction; each negative moves along −(u^−cjv^j)-(\hat u - c_j\hat v_j), away from it, with weight pjp_ju^−cjv^j\hat u - c_j\hat v_j is the component of u^\hat u orthogonal to v^j\hat v_j, the direction that turns vjv_j towards uu (Problem 2). A negative with tiny pjp_j, one the model already separates, is barely touched; a negative with pjp_j close to p1p_1 is pushed as hard as the positive is pulled. In a batch where every example is also a negative for the others, each vjv_j collects one such term from every anchor (Problem 9).

Problem 5

Show that the weight the loss puts on negative jj relative to negative kk is pj/pk=e(cj−ck)/τp_j/p_k = e^{(c_j - c_k)/\tau}. Describe pp and ∇cℓ\nabla_c\ell as τ→0\tau \to 0 and as τ→∞\tau \to \infty.

  1. pjpk=ecj/τeck/τ=e(cj−ck)/τ\dfrac{p_j}{p_k} = \dfrac{e^{c_j/\tau}}{e^{c_k/\tau}} = e^{(c_j - c_k)/\tau}.The common denominator of the softmax cancels.
  2. With τ=0.1\tau = 0.1, a negative whose similarity is 0.10.1 higher than another's gets e1≈2.7e^{1} \approx 2.7 times the weight; with τ=0.01\tau = 0.01, e10≈22,000e^{10} \approx 22{,}000 times.Step 1 with cj−ck=0.1c_j - c_k = 0.1.
  3. As τ→0\tau \to 0, p→ej∗p \to e_{j^*} where j∗j^* is the candidate with the largest similarity.The softmax page, Problem 9: softmax⁡(c/τ)\operatorname{softmax}(c/\tau) concentrates on the largest entry as the temperature goes to 00 (assuming a unique maximum).
  4. Then ∇cℓ=(p−y)/τ→(ej∗−e1)/τ\nabla_c\ell = (p - y)/\tau \to (e_{j^*} - e_1)/\tau: zero if the positive is the top candidate, and otherwise a push on the single hardest negative and a pull on the positive, each of size 1/τ1/\tau.Problem 1 with step 3. The loss itself tends to max⁡(0,max⁡j≠1cj−c1)/τ\max(0, \max_{j\neq1}c_j - c_1)/\tau, a hinge on the hardest negative.
  5. As τ→∞\tau \to \infty, p→1K1p \to \tfrac1K\mathbf{1} and ∇cℓ→(1K1−y)/τ→0\nabla_c\ell \to (\tfrac1K\mathbf{1} - y)/\tau \to 0.All logits go to 00, so the softmax is uniform; the 1/τ1/\tau then sends the gradient to zero.
  6. pj/pk=e(cj−ck)/τp_j/p_k = e^{(c_j - c_k)/\tau}; τ→0\tau \to 0 gives a hinge on the hardest negative with gradient (ej∗−e1)/τ(e_{j^*} - e_1)/\tau; τ→∞\tau \to \infty gives uniform weights and a vanishing gradientThe temperature is a hardness dial: small τ\tau makes the loss attend to the few negatives nearest the anchor, large τ\tau treats all negatives alike. Typical values (0.050.05 to 0.10.1 for SimCLR, about 0.010.01 for a trained CLIP) sit near the hard end, which is why these losses need many negatives: with few, the hardest negative is often not hard.

Problem 6

The symmetric batch loss used by CLIP is L=12N∑i=1N[ℓirow+ℓicol]L = \dfrac1{2N}\sum_{i=1}^N\big[\ell^{\text{row}}_i + \ell^{\text{col}}_i\big] with ℓirow=−Zii+log⁡∑jeZij\ell^{\text{row}}_i = -Z_{ii} + \log\sum_je^{Z_{ij}} (anchor uiu_i against all vjv_j) and ℓicol=−Zii+log⁡∑jeZji\ell^{\text{col}}_i = -Z_{ii} + \log\sum_je^{Z_{ji}} (anchor viv_i against all uju_j). Compute ∇ZL\nabla_ZL.

  1. ∂ℓirow/∂Zij=(Pr)ij−δij\partial\ell^{\text{row}}_i/\partial Z_{ij} = (P_r)_{ij} - \delta_{ij}, and ℓirow\ell^{\text{row}}_i does not depend on any other row of ZZ.Problem 1 applied to row ii of ZZ with label ii: its softmax is row ii of PrP_r.
  2. ∇Z∑iℓirow=Pr−I\nabla_Z\sum_i\ell^{\text{row}}_i = P_r - I.Stack step 1 over the rows: entry (i,j)(i, j) gets its contribution from ℓirow\ell^{\text{row}}_i alone.
  3. ∂ℓicol/∂Zji=(Pc)ji−δji\partial\ell^{\text{col}}_i/\partial Z_{ji} = (P_c)_{ji} - \delta_{ji}, and ℓicol\ell^{\text{col}}_i depends only on column ii.The same with column ii of ZZ and label ii; its softmax is column ii of PcP_c.
  4. ∇Z∑iℓicol=Pc−I\nabla_Z\sum_i\ell^{\text{col}}_i = P_c - I.Stack over the columns: entry (j,i)(j, i) comes from ℓicol\ell^{\text{col}}_i.
  5. ∇ZL=12N(Pr+Pc−2I)\nabla_ZL = \dfrac{1}{2N}\big(P_r + P_c - 2I\big)N×NN\times N, the shape of ZZ. Each row of Pr−IP_r - I and each column of Pc−IP_c - I sums to 00, so all the entries of ∇ZL\nabla_ZL sum to 00. The diagonal entries (Pr)ii+(Pc)ii−2(P_r)_{ii} + (P_c)_{ii} - 2 are negative (pull the pairs together) and the off-diagonal entries are positive (push every non-pair apart). Pc≠Pr⊤P_c \neq P_r^\top in general: the two directions normalise over different sets, so neither half can be dropped and recovered "by symmetry".

Problem 7

Show that ℓ\ell is unchanged by u→αuu \to \alpha u for any α>0\alpha > 0, that u⊤∇uℓ=0u^\top\nabla_u\ell = 0, and that ∇uℓ\nabla_u\ell evaluated at αu\alpha u is 1α\tfrac1\alpha times its value at uu. If u=Wxu = Wx for a projection WW and input xx, compute ∇Wℓ\nabla_W\ell.

  1. c(αu,v)=αu⊤vα∥u∥∥v∥=c(u,v)c(\alpha u, v) = \dfrac{\alpha u^\top v}{\alpha\|u\|\|v\|} = c(u, v).∥αu∥=α∥u∥\|\alpha u\| = \alpha\|u\| for α>0\alpha > 0; the α\alpha cancels. Every cjc_j, hence zz, pp and ℓ\ell, is unchanged.
  2. ddαℓ(αu)=u⊤∇uℓ(αu)\tfrac{d}{d\alpha}\ell(\alpha u) = u^\top\nabla_u\ell(\alpha u), and the left side is 00 for all α\alpha.Chain rule along the ray α↦αu\alpha \mapsto \alpha u; step 1 says ℓ\ell is constant on it. At α=1\alpha = 1, u⊤∇uℓ=0u^\top\nabla_u\ell = 0.
  3. ∇uℓ=1τ∑j(pj−yj)∇ucj\nabla_u\ell = \dfrac1\tau\sum_j(p_j - y_j)\nabla_uc_j, and each ∇ucj\nabla_uc_j at αu\alpha u is v^j−cju^α∥u∥\dfrac{\hat v_j - c_j\hat u}{\alpha\|u\|}, with pjp_j, cjc_j, u^\hat u unchanged.Problem 3, step 1, and Problem 2 with ∥αu∥=α∥u∥\|\alpha u\| = \alpha\|u\| and αu^=u^\widehat{\alpha u} = \hat u.
  4. So ∇uℓ(αu)=1α∇uℓ(u)\nabla_u\ell(\alpha u) = \tfrac1\alpha\nabla_u\ell(u).Every term is divided by α\alpha.
  5. ∇Wℓ=(∇uℓ) x⊤\nabla_W\ell = (\nabla_u\ell)\,x^\top.u=Wxu = Wx is linear in WW with xx fixed: ∂ℓ/∂Wab=∑i(∂ℓ/∂ui)(∂ui/∂Wab)=(∇uℓ)axb\partial\ell/\partial W_{ab} = \sum_i(\partial\ell/\partial u_i)(\partial u_i/\partial W_{ab}) = (\nabla_u\ell)_ax_b, the one-hidden-layer page's weight-gradient pattern.
  6. ℓ(αu)=ℓ(u)\ell(\alpha u) = \ell(u); u⊤∇uℓ=0u^\top\nabla_u\ell = 0; ∇uℓ(αu)=1α∇uℓ(u)\nabla_u\ell(\alpha u) = \tfrac1\alpha\nabla_u\ell(u); ∇Wℓ=(∇uℓ)x⊤\nabla_W\ell = (\nabla_u\ell)x^\topThe loss sees only the direction of uu, so its gradient can only turn uu, and it turns a long uu less: the effective learning rate on the direction falls as 1/∥u∥21/\|u\|^2 (one factor from the gradient, one from the angle a fixed step subtends). Nothing in the loss shrinks ∥u∥\|u\|, and ∥Wx∥\|Wx\| tends to grow under noisy gradient steps, so a scale-invariant loss relies on weight decay to keep its effective learning rate from decaying (the weight-decay page).

Problem 8

Compute ∂ℓ/∂τ\partial\ell/\partial\tau. CLIP learns the temperature through a logit scale s=1/τ=ets = 1/\tau = e^t with tt the trained parameter. Compute ∂ℓ/∂t\partial\ell/\partial t, and say which way tt moves when the positive's similarity exceeds the softmax-weighted average similarity.

  1. ℓ=−c1τ+log⁡∑jecj/τ\ell = -\dfrac{c_1}{\tau} + \log\sum_je^{c_j/\tau} with the cjc_j fixed.Problem 1's loss with zj=cj/τz_j = c_j/\tau written out.
  2. ∂∂τ(−c1τ)=c1τ2\dfrac{\partial}{\partial\tau}\Big(-\dfrac{c_1}{\tau}\Big) = \dfrac{c_1}{\tau^2}.ddττ−1=−τ−2\tfrac{d}{d\tau}\tau^{-1} = -\tau^{-2}.
  3. ∂∂τlog⁡∑jecj/τ=∑jpj⋅∂∂τcjτ=−1τ2∑jpjcj\dfrac{\partial}{\partial\tau}\log\sum_je^{c_j/\tau} = \sum_jp_j\cdot\dfrac{\partial}{\partial\tau}\dfrac{c_j}{\tau} = -\dfrac{1}{\tau^2}\sum_jp_jc_j.Chain rule through each logit: ∂ℓ/∂zj=pj\partial\ell/\partial z_j = p_j for the log-sum-exp part (Problem 1, step 2), and ∂zj/∂τ=−cj/τ2\partial z_j/\partial\tau = -c_j/\tau^2.
  4. ∂ℓ∂τ=c1−∑jpjcjτ2\dfrac{\partial\ell}{\partial\tau} = \dfrac{c_1 - \sum_jp_jc_j}{\tau^2}.Add steps 2 and 3.
  5. τ=e−t\tau = e^{-t}, so dτdt=−e−t=−τ\dfrac{d\tau}{dt} = -e^{-t} = -\tau and ∂ℓ∂t=∂ℓ∂τ⋅(−τ)=−c1−∑jpjcjτ\dfrac{\partial\ell}{\partial t} = \dfrac{\partial\ell}{\partial\tau}\cdot(-\tau) = -\dfrac{c_1 - \sum_jp_jc_j}{\tau}.s=et=1/τs = e^t = 1/\tau inverts to τ=e−t\tau = e^{-t}; chain rule.
  6. ∂ℓ∂τ=c1−∑jpjcjτ2\dfrac{\partial\ell}{\partial\tau} = \dfrac{c_1 - \sum_jp_jc_j}{\tau^2} and ∂ℓ∂t=∑jpjcj−c1τ\dfrac{\partial\ell}{\partial t} = \dfrac{\sum_jp_jc_j - c_1}{\tau}; when c1>∑jpjcjc_1 > \sum_jp_jc_j, ∂ℓ/∂t<0\partial\ell/\partial t < 0, so gradient descent increases tt and decreases τ\tauWhen the positive beats the weighted average, sharpening the softmax lowers the loss, so the model learns a smaller temperature; when the positive is losing, it learns a larger one to soften the penalty. Left unbounded, a model that is winning sharpens without limit, which is why CLIP clips the logit scale at 100100 (τ≥0.01\tau \ge 0.01). The ∑jpjcj\sum_jp_jc_j is the loss's own expectation of the similarity under pp.

Problem 9

For the symmetric batch loss of Problem 6 with Z=U^V^⊤/τZ = \hat U\hat V^\top/\tau, compute ∇U^L\nabla_{\hat U}L and ∇V^L\nabla_{\hat V}L in matrix form, then ∇uiL\nabla_{u_i}L through the normalisation u^i=ui/∥ui∥\hat u_i = u_i/\|u_i\|.

Write Γ=∇ZL=12N(Pr+Pc−2I)\Gamma = \nabla_ZL = \tfrac1{2N}(P_r + P_c - 2I) from Problem 6.

  1. Z=1τU^V^⊤Z = \tfrac1\tau\hat U\hat V^\top has U^\hat U as its left factor and V^⊤\hat V^\top as its right factor.A matrix product scaled by a constant.
  2. ∇U^L=1τΓV^\nabla_{\hat U}L = \tfrac1\tau\Gamma\hat V, N×dN\times d.The attention page's left-factor pattern: for C=PRC = PR, ∇PL=(∇CL)R⊤\nabla_PL = (\nabla_CL)R^\top, with R=V^⊤R = \hat V^\top and the constant 1/τ1/\tau carried along.
  3. ∇V^L=1τΓ⊤U^\nabla_{\hat V}L = \tfrac1\tau\Gamma^\top\hat U, N×dN\times d.The right-factor pattern ∇RL=P⊤∇CL\nabla_RL = P^\top\nabla_CL gives ∇V^⊤L=1τU^⊤Γ\nabla_{\hat V^\top}L = \tfrac1\tau\hat U^\top\Gamma; transpose to get the gradient with respect to V^\hat V.
  4. Row ii of U^\hat U depends on uiu_i alone, so ∇uiL=(∂u^i∂ui)⊤(∇U^L)i,:⊤=1∥ui∥(I−u^iu^i⊤)(∇U^L)i,:⊤\nabla_{u_i}L = \Big(\dfrac{\partial\hat u_i}{\partial u_i}\Big)^\top(\nabla_{\hat U}L)_{i,:}^\top = \dfrac{1}{\|u_i\|}(I - \hat u_i\hat u_i^\top)(\nabla_{\hat U}L)_{i,:}^\top.Chain rule through the normalisation with the Jacobian from Before you start, which is symmetric; the upstream gradient at u^i\hat u_i is row ii of step 2, as a column.
  5. ∇U^L=1τΓV^\nabla_{\hat U}L = \tfrac1\tau\Gamma\hat V, ∇V^L=1τΓ⊤U^\nabla_{\hat V}L = \tfrac1\tau\Gamma^\top\hat U, Γ=12N(Pr+Pc−2I)\Gamma = \tfrac1{2N}(P_r + P_c - 2I); then ∇uiL=1∥ui∥(I−u^iu^i⊤)(1τΓV^)i,:⊤\nabla_{u_i}L = \dfrac{1}{\|u_i\|}(I - \hat u_i\hat u_i^\top)\big(\tfrac1\tau\Gamma\hat V\big)_{i,:}^\top, and likewise for viv_i with Γ⊤U^\Gamma^\top\hat URow ii of ΓV^\Gamma\hat V is ∑jΓijv^j\sum_j\Gamma_{ij}\hat v_j: the positive v^i\hat v_i with negative weight, every other v^j\hat v_j with positive weight, which is Problem 3 for anchor uiu_i plus the terms from uiu_i serving as a negative for the other anchors through PcP_c. The projection then drops the part along u^i\hat u_i and the 1/∥ui∥1/\|u_i\| scales it, exactly as in Problem 2. The whole backward pass is two matrix products and a row-wise projection; the N×NN\times N matrix Γ\Gamma is the only thing that scales with the batch.

Problem 10

Suppose the logits were the plain dot products zj=u⊤vj/τz_j = u^\top v_j/\tau with no normalisation. Compute ∇uℓ\nabla_u\ell and u⊤∇uℓu^\top\nabla_u\ell, and show that when the positive has the largest logit the loss can be reduced by scaling uu up, without changing its direction.

  1. ∇uℓ=∑j(pj−yj)∇uzj=1τ∑j(pj−yj)vj\nabla_u\ell = \sum_j(p_j - y_j)\nabla_uz_j = \dfrac1\tau\sum_j(p_j - y_j)v_j.Problem 1's ∇zℓ=p−y\nabla_z\ell = p - y and ∇u(u⊤vj/τ)=vj/τ\nabla_u(u^\top v_j/\tau) = v_j/\tau.
  2. u⊤∇uℓ=1τ∑j(pj−yj)u⊤vj=∑j(pj−yj)zj=∑jpjzj−z1u^\top\nabla_u\ell = \dfrac1\tau\sum_j(p_j - y_j)u^\top v_j = \sum_j(p_j - y_j)z_j = \sum_jp_jz_j - z_1.u⊤vj/τ=zju^\top v_j/\tau = z_j, and yy picks out z1z_1.
  3. ddαℓ(αu)∣α=1=u⊤∇uℓ=∑jpjzj−z1\tfrac{d}{d\alpha}\ell(\alpha u)\big|_{\alpha=1} = u^\top\nabla_u\ell = \sum_jp_jz_j - z_1.Chain rule along the ray, as in Problem 7, step 2. Here it is not zero.
  4. If z1>zjz_1 > z_j for every j≠1j \neq 1 then ∑jpjzj<z1\sum_jp_jz_j < z_1, so the derivative is negative.A weighted average of the zjz_j with weights pj>0p_j > 0 summing to 11 is strictly less than the largest of them when the others are smaller.
  5. The same holds at every α>0\alpha > 0, since zj(αu)=αzj(u)z_j(\alpha u) = \alpha z_j(u) keeps the ordering.Scaling uu scales every logit by the same positive factor; the positive stays on top and step 4 applies again.
  6. ∇uℓ=1τ∑j(pj−yj)vj\nabla_u\ell = \tfrac1\tau\sum_j(p_j - y_j)v_j, u⊤∇uℓ=∑jpjzj−z1u^\top\nabla_u\ell = \sum_jp_jz_j - z_1; when the positive leads, ℓ(αu)\ell(\alpha u) decreases in α\alpha, so the loss rewards growing ∥u∥\|u\|With dot-product logits, the encoder can drive ℓ→0\ell \to 0 on every example it already gets right by inflating embedding norms, which sharpens the softmax without learning anything new about directions; the gradient has a component along uu that does exactly this. Normalising removes that component (Problem 7) and the temperature puts the sharpness back under control (Problem 5): cosine plus τ\tau is dot product with the norm fixed at 1/τ1/\tau.

Where this goes wrong

1. Cosine gradient as a dot-product gradient

Once u^\hat u and v^\hat v are computed, c=u^⊤v^c = \hat u^\top\hat v looks like a dot product with two constant vectors.

  1. c(u,v)=u^⊤v^c(u, v) = \hat u^\top\hat vRight so far.
  2. “∇u(u⊤a)=a\nabla_u(u^\top a) = a, and here a=v^/∥u∥a = \hat v/\|u\|.”The shortcut that causes the mistake: ∥u∥\|u\| in the denominator is treated as a constant, when it is a function of uu with gradient u^\hat u.
  3. ∇uc=v^∥u∥\nabla_uc = \dfrac{\hat v}{\|u\|}The missing term is −c u^∥u∥-\dfrac{c\,\hat u}{\|u\|} (Problem 2), the part of the answer that makes u⊤∇uc=0u^\top\nabla_uc = 0. The wrong gradient has u⊤∇uc=cu^\top\nabla_uc = c, so a descent step changes ∥u∥\|u\|: it shrinks the anchor when the positive is similar and grows it when a negative is, and the scale invariance of Problem 7 is gone. The two agree only when c=0c = 0.

2. Dropping the 1/τ

The temperature is a constant, and p−yp - y is the gradient everyone remembers.

  1. ∇zℓ=p−y\nabla_z\ell = p - yRight so far: Problem 1.
  2. “The similarities are the logits up to a constant, so their gradient is the same.”The shortcut that causes the mistake: a constant factor in the forward pass is a constant factor in the backward pass.
  3. ∇cℓ=p−y\nabla_c\ell = p - yIt is (p−y)/τ(p - y)/\tau (Problem 1), and with τ=0.07\tau = 0.07 the gradient reaching the encoder is 1414 times too small. A fixed τ\tau makes this a learning-rate error on the encoder only, while a learned temperature (Problem 8) and any other loss terms keep their true scale, so the balance between them is wrong and no learning-rate sweep fixes it.

3. Symmetric loss computed in one direction

Half the CLIP loss is a cross-entropy over rows of ZZ, and the other half looks like the same thing again.

  1. ∇Z∑iℓirow=Pr−I\nabla_Z\sum_i\ell^{\text{row}}_i = P_r - IRight so far: Problem 6, step 2.
  2. “The column direction is the same loss with the roles swapped, so it gives the same gradient; just double the row loss.”The assumption that causes the mistake: the row softmax normalises each uiu_i over all vjv_j, the column softmax each viv_i over all uju_j; the two sets of weights are different.
  3. ∇ZL=1N(Pr−I)\nabla_ZL = \tfrac1N(P_r - I)The gradient is 12N(Pr+Pc−2I)\tfrac1{2N}(P_r + P_c - 2I) (Problem 6), and Pc≠Pr⊤P_c \neq P_r^\top. With rows only, a text vjv_j is never an anchor: it is pushed by the images' softmaxes but never gets its own competition among images, so a text that is similar to many images is never penalised for it. Training runs, and the retrieval in the text-to-image direction is measurably worse.

4. Normalisation backward without the projection

u^=u/∥u∥\hat u = u/\|u\| is a division by a number, and dividing the upstream gradient by the same number looks like the backward pass.

  1. ∇u^ℓ=1τ∑j(pj−yj)v^j\nabla_{\hat u}\ell = \dfrac1\tau\sum_j(p_j - y_j)\hat v_jRight so far: the gradient at the unit vector, before the normalisation.
  2. “u^=u/∥u∥\hat u = u/\|u\|, so ∇uℓ=∇u^ℓ/∥u∥\nabla_u\ell = \nabla_{\hat u}\ell/\|u\|.”The shortcut that causes the mistake: ∥u∥\|u\| is held fixed, so the Jacobian 1∥u∥(I−u^u^⊤)\tfrac1{\|u\|}(I - \hat u\hat u^\top) loses its projection.
  3. ∇uℓ=1∥u∥⋅1τ∑j(pj−yj)v^j\nabla_u\ell = \dfrac{1}{\|u\|}\cdot\dfrac1\tau\sum_j(p_j - y_j)\hat v_jThe true gradient is this with (I−u^u^⊤)(I - \hat u\hat u^\top) applied (Problem 9, step 4), which subtracts the component along u^\hat u: 1τ∥u∥(∑jpjcj−c1)u^\tfrac{1}{\tau\|u\|}(\sum_jp_jc_j - c_1)\hat u (Problem 3). The wrong gradient is not orthogonal to uu; when the positive leads it points along −u-u, so the step grows the anchor, and the norm drift Problem 10 warned about comes back through the backward pass even though the forward pass normalises.

5. Temperature gradient with the wrong sign

The learned parameter is the logit scale s=ets = e^t, and the derivative with respect to τ\tau is the one that is easy to write down.

  1. ∂ℓ∂τ=c1−∑jpjcjτ2\dfrac{\partial\ell}{\partial\tau} = \dfrac{c_1 - \sum_jp_jc_j}{\tau^2}Right so far: Problem 8, step 4.
  2. “tt parametrises the temperature, so update tt with the temperature's gradient.”The slip that causes the mistake: τ=e−t\tau = e^{-t} decreases in tt, and the chain rule carries the factor dτ/dt=−τd\tau/dt = -\tau.
  3. ∂ℓ∂t=c1−∑jpjcjτ2\dfrac{\partial\ell}{\partial t} = \dfrac{c_1 - \sum_jp_jc_j}{\tau^2}The gradient is −τ-\tau times this, ∑jpjcj−c1τ\dfrac{\sum_jp_jc_j - c_1}{\tau} (Problem 8): opposite sign and a different scale. With the wrong sign, a model whose positives are winning softens its softmax instead of sharpening it, and tt runs away in the wrong direction until the clip at s=100s = 100 or at s→0s \to 0 stops it. Autodiff does not make this mistake; a hand-written update, or a schedule that adjusts τ\tau directly from ∂ℓ/∂τ\partial\ell/\partial\tau while the model stores tt, does.

Print this set: contrastive-loss-and-infonce-gradient.pdf (problems, answers, and worked solutions on separate pages).