Implement contrastive loss and its gradient for Siamese embedding pairs
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Given paired embeddings `x1` and `x2` of shape `(N, D)` and labels `y` (1 = similar, 0 = dissimilar), implement `contrastive_loss(x1, x2, y, margin=1.0, reduction="mean")` using the per-pair loss
$$L_i = y_i\, d_i^2 + (1 - y_i)\max(0,\ \text{margin} - d_i)^2$$
where $d_i$ is the Euclidean distance between row $i$ of `x1` and row $i$ of `x2` (there is no 1/2 factor). Also implement `contrastive_loss_grad(x1, x2, y, margin=1.0)`, returning the gradient of the mean loss with respect to `x1` (shape `(N, D)`).
For example:
```text
x1 = [[0, 0], [1, 1], [0, 0]]
x2 = [[3, 4], [1, 1], [0.3, 0.4]]
y = [1, 0, 0], margin = 1.0
per-pair (reduction="none"): [25.0, 1.0, 0.25]
Output (reduction="mean"): 8.75
```
```hint Chain rule through the distance
Write out $\partial d_i / \partial x_{1,i}$ and substitute it into each of the two terms. Look at which term still divides by $d_i$ afterwards.
```
### Constraints & Assumptions
- `reduction` is `"none"` (array of N losses), `"sum"` or `"mean"` (Python `float`). Any other value raises `ValueError`.
- A dissimilar pair with `d >= margin` contributes zero loss and zero gradient.
- The gradient must be finite: a dissimilar pair with `d = 0` gets zero gradient.
- Inputs may be lists or NumPy arrays. `margin > 0`.
### What a Strong Answer Covers
- Row-wise Euclidean distances and the two loss terms, with the squared hinge, reproducing the example values.
- All three reductions, a `ValueError` for any other value, and Python floats for `"sum"` and `"mean"`.
- The gradient derived with the chain rule through $d$, including the ${1/N}$ factor of the mean and the sign of the dissimilar term.
- Zero gradient for inactive dissimilar pairs and a finite result at $d = 0$ without dividing by zero.
### Follow-up Questions
- What is the gradient with respect to `x2`, and how does it reach a shared encoder in a Siamese network?
- Why square the hinge? What changes if the dissimilar term is `max(0, margin - d)` without the square?
- How would you choose the margin, and why does it matter whether the embeddings are L2-normalized?
Overview: Implement the margin-based contrastive loss for pairs of embeddings in NumPy, with none, sum and mean reductions, plus its gradient with respect to the first embedding. Tests the chain rule through Euclidean distance, the squared hinge, and keeping the gradient finite at zero distance.