CrackML by @ml.with.umang
Interview questions / ML Coding & PyTorch
ML Coding & PyTorch interview question

Implement a Contrastive Learning Loss

Implement an InfoNCE-style contrastive loss for paired embeddings.

hardml codingEvidence 41/1001 source reportLinkedIn

The 60-second answer

Normalize embeddings if cosine similarity is intended, build the pairwise similarity matrix, and divide logits by a temperature parameter. Define the positive mapping explicitly and treat the other batch examples as negatives; use cross-entropy over the similarity logits.

Build the answer in this order

1
State tensor contract

Normalize embeddings if cosine similarity is intended, build the pairwise similarity matrix, and divide logits by a temperature parameter.

2
Implement the mechanism

Define the positive mapping explicitly and treat the other batch examples as negatives; use cross-entropy over the similarity logits.

3
Check numerics + gradients

Decide whether the loss is symmetric across both views and how duplicate/false-negative examples are handled.

4
Test shapes and edge cases

Test with identical positive pairs, shuffled labels, very small temperature, and gradients on both embedding branches.

A useful interview mental model

This is the shape of a strong answer—not a script to memorize.

01Shapes
02Forward pass
03Loss / grads
04Numerics
05Tests

Senior-level signal

  • Senior answers discuss batch-size dependence, false negatives, hard-negative mining, and distributed all-gather for cross-worker negatives.
  • Explain why temperature changes both probability sharpness and gradient scale.

What the interviewer is really testing

Tensor fluency, shape reasoning, numerics, gradients, batching, device awareness, and the ability to debug—not API memorization.

Likely follow-up questions

What are the tensor shapes at each step?
Where could numerical instability or silent broadcasting appear?
How would you verify gradients and batched behavior?

Common weak-answer patterns

  • Ignoring shape, dtype, device, masking, or broadcasting assumptions.
  • Using a framework call without explaining the underlying operation.
  • Skipping gradient, numerical-stability, and batching checks.