Derive the gradient of cosine similarity with respect to one vector
Contrastive embedding training pushes the cosine similarity of matching pairs up. To do that you need the gradient of cos(x, y) = x.y / (|x| |y|) with respect to x.
Write cosine_grad(x, y) for 1D float arrays of equal length. Return the gradient of cos(x, y) with respect to x, shape like x. If x or y is the zero vector, return zeros.
Check: the gradient is always orthogonal to x, because scaling x does not change the cosine.
def cosine_grad(x, y)Example
x = [1, 0], y = [1, 1] gives [0.0, 0.70710678].
Understand the idea
Cosine similarity depends only on direction, so making x longer cannot change it. Its gradient with respect to x has two parts: y / (|x| |y|) pulls x toward y, and - cos x x / |x|^2 removes the part that would only stretch x. The result is always at right angles to x. Worked example: x = [1, 1], y = [1, 0]. |x| = 1.414, |y| = 1, cos = 1 / 1.414 = 0.707. First term: [1, 0] / 1.414 = [0.707, 0]. Second term: 0.707 x [1, 1] / 2 = [0.354, 0.354]. Gradient = [0.354, -0.354]. Check: its dot product with x is 0.354 - 0.354 = 0. Dropping the second term would give a gradient that also rewards making x longer. If x or y is all zeros, return zeros. Rule: d cos / dx = y / (|x||y|) - cos(x, y) x / |x|^2. Contrastive embedding training, such as sentence embedding models, backpropagates through this.