Implement the NT-Xent Contrastive Loss and Its Gradient in NumPy

Quick Overview

Implement the NT-Xent contrastive loss for two views of a batch in NumPy, plus its gradient with respect to the raw embeddings. Tests masked softmax over in-batch negatives, numerical stability at very small temperatures, and backpropagation through L2 normalization.

Implement the NT-Xent Contrastive Loss and Its Gradient in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Given two views `z1` and `z2` (each `n × d`, where row `i` of each forms a positive pair), implement `nt_xent_loss(z1, z2, temperature=0.5)` returning the mean NT-Xent loss as a `float`, and `nt_xent_grad(z1, z2, temperature=0.5)` returning `(grad_z1, grad_z2)` with respect to the raw (unnormalized) embeddings. Stack `z = [z1; z2]` (2n rows), L2-normalize each row to `u`, and average over all 2n anchors: ```text s[i, j] = u[i] @ u[j] / temperature loss_i = logsumexp(s[i, j] for j != i) - s[i, (i + n) % (2 * n)] loss = mean(loss_i) # over the 2n anchors ``` Example: ```python z1 = [[1, 0], [0, 1]] z2 = [[1, 0], [0, 1]] nt_xent_loss(z1, z2, temperature=1.0) # log(e + 2) - 1, about 0.551445 nt_xent_grad(z1, z2, temperature=1.0) # grad_z1 and grad_z2 both equal [[0, 1/(e + 2)], [1/(e + 2), 0]], # about [[0, 0.211942], [0.211942, 0]] ``` ```hint Read each anchor as a classifier Each anchor's loss has the form of softmax cross-entropy over a set of candidates. Decide which candidate is the correct class and which logit has to be left out. ``` ```hint Small temperatures At `temperature = 1e-3` the logits reach about 1000. Pick a shift that keeps `exp` finite, and check how the excluded entry behaves under it. ``` ```hint Two chain-rule steps Every `u[k]` appears in `s` twice, once in its row and once in its column. After that, the gradient still has to pass back through the row normalization. ``` ### Constraints & Assumptions - `n ≥ 1` and every row is non-zero. With `n = 1` the loss is `0.0`. - Raise `ValueError` if the inputs are not 2-D arrays of identical shape, or if `temperature <= 0`. - The loss and gradients must stay finite for `temperature` as small as `1e-3`. - The gradients have the same shapes as `z1` and `z2` and must match finite differences (rtol `1e-5`). - Use `numpy` only. ### What a Strong Answer Covers - Stacking the two views, normalizing the rows, and excluding self-similarity from each anchor's softmax. - A shifted logsumexp that stays finite at very small temperatures. - The gradient with respect to the similarity logits and its pass back to `u`, accounting for both places each row appears. - The Jacobian of the row normalization and the split of the result into `grad_z1` and `grad_z2`. - The `n = 1` case, the input validation, and a finite-difference check of the gradients. ### Follow-up Questions - Why is each row's gradient orthogonal to its embedding? - How does temperature affect learning dynamics? - How would you scale this to very large batches or multiple GPUs?

Overview: Implement the NT-Xent contrastive loss for two views of a batch in NumPy, plus its gradient with respect to the raw embeddings. Tests masked softmax over in-batch negatives, numerical stability at very small temperatures, and backpropagation through L2 normalization.

PracHub logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Given two views z1 and z2 (each n × d, where row i of each forms a positive pair), implement nt_xent_loss(z1, z2, temperature=0.5) returning the mean NT-Xent loss as a float, and nt_xent_grad(z1, z2, temperature=0.5) returning (grad_z1, grad_z2) with respect to the raw (unnormalized) embeddings.

Stack z = [z1; z2] (2n rows), L2-normalize each row to u, and average over all 2n anchors:

s[i, j] = u[i] @ u[j] / temperature
loss_i  = logsumexp(s[i, j] for j != i) - s[i, (i + n) % (2 * n)]
loss    = mean(loss_i)   # over the 2n anchors

Example:

z1 = [[1, 0], [0, 1]]
z2 = [[1, 0], [0, 1]]
nt_xent_loss(z1, z2, temperature=1.0)   # log(e + 2) - 1, about 0.551445
nt_xent_grad(z1, z2, temperature=1.0)
# grad_z1 and grad_z2 both equal [[0, 1/(e + 2)], [1/(e + 2), 0]],
# about [[0, 0.211942], [0.211942, 0]]

Constraints & Assumptions

  • n ≥ 1 and every row is non-zero. With n = 1 the loss is 0.0 .
  • Raise ValueError if the inputs are not 2-D arrays of identical shape, or if temperature <= 0 .
  • The loss and gradients must stay finite for temperature as small as 1e-3 .
  • The gradients have the same shapes as z1 and z2 and must match finite differences (rtol 1e-5 ).
  • Use numpy only.

What a Strong Answer Covers Guidance

  • Stacking the two views, normalizing the rows, and excluding self-similarity from each anchor's softmax.
  • A shifted logsumexp that stays finite at very small temperatures.
  • The gradient with respect to the similarity logits and its pass back to u , accounting for both places each row appears.
  • The Jacobian of the row normalization and the split of the result into grad_z1 and grad_z2 .
  • The n = 1 case, the input validation, and a finite-difference check of the gradients.

Follow-up Questions Guidance

  • Why is each row's gradient orthogonal to its embedding?
  • How does temperature affect learning dynamics?
  • How would you scale this to very large batches or multiple GPUs?