Cosine Embedding Loss With Safe Norms
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `cosine_embedding_loss(x1, x2, y, margin=0.0, reduction="mean", eps=1e-8)` over paired rows of `x1` and `x2`, both of shape `(N, D)`. For each row compute `cos = dot(a, b) / max(‖a‖·‖b‖, eps)`. The clamp applies to the product of the two norms; do not clamp each norm separately. The per-pair loss is `1 - cos` when `y = 1` and `max(0, cos - margin)` when `y = -1`.
- `reduction="mean"` or `"sum"` returns a Python `float`. `"none"` returns an array of shape `(N,)`.
- Any other `reduction` raises `ValueError`.
- Non-2-D or mismatched `x1`/`x2`, the wrong number of labels, or labels outside `{+1, -1}` raise `ValueError`.
- Zero vectors must give `cos = 0` with no floating-point warnings or errors.
For example:
```text
x1 = [[1, 0], [1, 0], [0, 1]]
x2 = [[1, 0], [0, 1], [1, 1]]
y = [1, -1, 1]
reduction="none" -> [0.0, 0.0, 0.29289] # 1 - 1/sqrt(2)
reduction="mean" -> 0.09763
```
```hint Vectorize over rows
Sums along `axis=1` give every row's dot product and squared norms in one call each. Before running anything, check what your formula does when one row is all zeros.
```
### Constraints & Assumptions
- Inputs may be lists or arrays. Convert them to `float`.
- `margin` may be negative. `eps > 0`.
- Use NumPy only, vectorized over rows (no Python loop over pairs).
### What a Strong Answer Covers
- Validation of shapes, label count, label values and the reduction name, each raising `ValueError`.
- Row-wise dot products and norms computed with vectorized NumPy operations.
- A denominator clamped with `max` on the norm product, so zero vectors give `cos = 0` without division warnings.
- Correct per-pair branching on the label, including a negative `margin`.
- The right return types: a Python `float` for `"mean"` and `"sum"`, an `(N,)` array for `"none"`.
### Follow-up Questions
- Why clamp `‖a‖·‖b‖` with `max` instead of adding `eps` to the denominator?
- What is the gradient of the loss with respect to `x1` for a `y = 1` pair, and how does it behave when that row is close to zero?
- Entries around `1e200` overflow when squared. How would you keep the norms finite?
- How do the sign and size of `margin` change what the loss asks of dissimilar pairs?
Overview: Implement cosine embedding loss in NumPy over paired embedding rows, with mean, sum and none reductions and strict input validation. It tests vectorized row-wise math, safe handling of zero vectors through a clamped norm product, and careful return types.