InfoNCE Loss: One True Match Among Negatives

Loss FunctionsHard+10 XP+10

InfoNCE Loss: One True Match Among Negatives

InfoNCE is what contrastive learning methods like SimCLR and CLIP optimize. For each query, treat its matching key (same index) as the one positive among a batch full of negatives, and turn similarity scores into a classification problem.

Li=−log⁡exp⁡(sim(qi,ki)/τ)∑jexp⁡(sim(qi,kj)/τ)L_i = -\log \frac{\exp(\text{sim}(q_i, k_i) / \tau)}{\sum_j \exp(\text{sim}(q_i, k_j) / \tau)}Li​=−log∑j​exp(sim(qi​,kj​)/τ)exp(sim(qi​,ki​)/τ)​

Task: write infonce_loss(queries, keys, temperature) using the dot product as sim, returning the mean of L_i over the batch, rounded to 4 decimal places.

  • queries[i] is only ever compared against keys[i] as its positive — every other key in the batch counts as a negative for it.
  • A lower temperature sharpens the distribution, making the model pay more for confusing a negative with the positive.

Examples

queries = [[1.0, 0.0], [0.0, 1.0]]
keys = [[1.0, 0.0], [0.0, 1.0]]
temperature = 0.5
returns 0.1269
queries = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
keys = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
temperature = 1.0
returns 0.7585

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run