Vectorized RankNet Loss and Gradient
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given 1-D arrays `scores` and `relevance` and a scale `sigma`, implement `ranknet_loss(scores, relevance, sigma=1.0)`, which returns a `float`, and `ranknet_grad(scores, relevance, sigma=1.0)`, which returns an array shaped like `scores`. The loss is the mean of `log(1 + exp(-sigma * (s[i] - s[j])))` over all ordered pairs `(i, j)` with `relevance[i] > relevance[j]`. The gradient is the exact derivative of that mean loss with respect to each score.
For example:
```python
ranknet_loss([2.0, 1.0, 0.0], [2, 1, 0], sigma=1.0)
# (2 * log1p(exp(-1)) + log1p(exp(-2))) / 3, about 0.25115
ranknet_grad([2.0, 1.0, 0.0], [2, 1, 0], sigma=1.0)
# about [-0.12938, 0.0, 0.12938]
ranknet_loss([1000.0, -1000.0], [0, 1]) # 2000.0
ranknet_grad([1000.0, -1000.0], [0, 1]) # [1.0, -1.0]
```
```hint Pairs as a matrix
Every quantity here is indexed by a pair `(i, j)`. Build it as an `(n, n)` array with broadcasting, and use a boolean mask to keep only the pairs that count.
```
```hint Extreme gaps
At a score gap of 2000, `exp` overflows. Look for NumPy functions that give `log(1 + exp(x))` and the logistic sigmoid without ever computing `exp` of a large positive number.
```
### Constraints & Assumptions
- Pairs with tied relevance are ignored.
- If no pair qualifies, the loss is `0.0` and the gradient is all zeros.
- Mismatched lengths raise `ValueError`.
- Results must stay finite and accurate for scores up to ±1000.
- Vectorize with NumPy, with no Python loops over pairs.
### What a Strong Answer Covers
- A broadcast `(n, n)` difference matrix and a relevance mask that drops ties and the diagonal.
- A loss computed with a stable form of `log(1 + exp(x))`, averaged over the qualifying pairs only.
- The per-pair derivative, how it splits between the two documents of a pair, and the row and column sums that collect it.
- The no-pairs case, the length check, and the numerical behavior at a score gap of 2000.
- Time and memory cost in terms of the list length `n`.
### Follow-up Questions
- How would you turn this into LambdaRank?
- Memory grows as `O(n^2)`. How would you scale to lists with thousands of documents?
- Why use `np.logaddexp` and a tanh-based sigmoid instead of the naive formulas?
Overview: Implement the RankNet pairwise ranking loss and its exact gradient in NumPy, averaged over document pairs whose relevance differs. It tests building pairwise matrices with broadcasting, deriving per-pair gradients, and keeping the loss and sigmoid numerically stable for score gaps in the thousands.