Implement Triplet Loss, Its Gradient and Semi-Hard Negative Mining in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement five NumPy functions for triplet metric learning. Distances are Euclidean, and the loss for one triplet (anchor $a$, positive $p$, negative $n$) is
$$
\max\left(0,\ \lVert a - p \rVert - \lVert a - n \rVert + \text{margin}\right)
$$
- `pairwise_distances(embeddings, squared=False)` returns a vectorized `(n, n)` distance matrix (squared distances when `squared=True`). Clamp negative values to 0, set the diagonal to exactly 0, and never return NaN. Duplicate rows must get distance 0.
- `triplet_margin_loss(anchor, positive, negative, margin=1.0, reduction="mean")` computes the loss per row. `"mean"` and `"sum"` return a `float`, `"none"` returns the per-row array, and any other value raises `ValueError`.
- `triplet_margin_loss_grad(anchor, positive, negative, margin=1.0)` returns the analytic gradients of the mean loss as `(ga, gp, gn)`. Inactive triplets (hinge $\le 0$) get zero gradient, and a zero distance uses a zero unit vector.
- `mine_semi_hard_negatives(embeddings, labels)` visits each anchor `i` and each positive `j != i` with the same label, both in ascending order. For each pair it picks the closest negative `k` with `d(i, k) > d(i, j)`. If no negative qualifies, it picks the farthest negative. Ties go to the lowest index, and anchors with no negatives are skipped. It returns three `int64` arrays (anchors, positives, negatives).
- `batch_semi_hard_triplet_loss(embeddings, labels, margin=1.0)` returns the mean hinge loss over the mined triplets, or `0.0` when there are none.
On this batch of one-dimensional embeddings the expected results are:
```python
emb = [[0.0], [1.0], [3.0], [1.5], [5.0]]
labels = [0, 0, 0, 1, 1]
mine_semi_hard_negatives(emb, labels)
# a = [0, 0, 1, 1, 2, 2, 3, 4]
# p = [1, 2, 0, 2, 0, 1, 4, 3]
# k = [3, 4, 4, 4, 4, 4, 0, 1]
batch_semi_hard_triplet_loss(emb, labels, margin=1.0) # 0.875
```
```hint Distance matrix pitfall
The expansion $\lVert x_i \rVert^2 + \lVert x_j \rVert^2 - 2\, x_i \cdot x_j$ subtracts large, nearly equal numbers. Ask what it returns for two identical rows, or after adding the same large vector to every embedding.
```
```hint Gradient
Differentiate $\lVert a - p \rVert$ with respect to $a$ and to $p$ separately, and remember that the mean reduction scales every row.
```
```hint Mining order and ties
Trace anchors 2 and 3 of the example by hand. Anchor 2 has a negative at exactly its positive's distance, and anchor 3 has two negatives at the same distance.
```
### Constraints & Assumptions
- Embeddings are finite with shape `(n, d)`. The triplet inputs `anchor`, `positive` and `negative` share one shape `(m, d)`.
- `labels` has length `n`.
- Results must be translation invariant: adding the same vector to every embedding must not change any output beyond rounding.
### What a Strong Answer Covers
- A vectorized distance matrix that is non-negative, exactly zero on the diagonal and for duplicate rows, and stable when every embedding is shifted by a large vector.
- The three reductions, the `ValueError` path, and a gradient of the mean loss that is scaled by the number of triplets, is zero for inactive triplets, and handles zero distances.
- Mining that follows the stated visiting order, the strict inequality, the farthest-negative fallback, the lowest-index tie rule, and skipping anchors with no negatives.
- A check against the example (and ideally a numerical gradient check), plus the time and memory cost of the distance matrix and the mining step.
### Follow-up Questions
- How would batch-hard mining differ, and when would you prefer it?
- Why is the gradient at zero distance a problem, and how do squared distances change things?
- How would you vectorize the mining step for large batches?
Overview: Implement triplet margin loss, its analytic gradient and semi-hard negative mining in NumPy for metric learning. Tests a numerically stable pairwise distance matrix, hinge gradients with zero-distance handling, and exact ordering and tie rules when selecting negatives.