ListNet Top-One Loss with Padding Masks
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given `scores`, `relevance` and a boolean `mask`, all of shape `(n, L)` (n queries, each padded to length L), implement two functions:
```python
def listnet_loss(scores, relevance, mask, reduction="mean") -> float: ...
def listnet_grad(scores, relevance, mask) -> np.ndarray: ...
```
Each query's loss is the cross-entropy $-\sum_j \text{softmax}(y)_j \log \text{softmax}(s)_j$, where both softmaxes run over the valid (unmasked) positions only. `listnet_grad` returns the gradient of the mean-reduced loss with respect to `scores`, with the same shape as the input.
For example:
```python
scores = [[1.0, 0.0, 7.0], [0.0, 0.0, 0.0]]
relevance = [[0.0, 0.0, -3.0], [0.0, 0.0, 0.0]]
mask = [[True, True, False], [False, False, False]]
listnet_loss(scores, relevance, mask) # 0.813262 (query 2 is empty, excluded)
listnet_grad(scores, relevance, mask) # [[0.231059, -0.231059, 0.0], [0.0, 0.0, 0.0]]
```
In query 1 only the first two slots count, so the `7.0` and `-3.0` in the padded slot have no effect on either output.
```hint Stability
Values near 1000 overflow `exp`. Think about which shift keeps every exponent at or below zero, and which entries that shift should be computed over.
```
```hint Gradient
Write the derivative of softmax cross-entropy with respect to the logits for a single query, then work out how averaging over queries scales it.
```
### Constraints & Assumptions
- `reduction` is `"mean"` (average over queries with at least one valid item) or `"sum"`. Any other value raises `ValueError`.
- Inputs that are not 2-D or have mismatched shapes raise `ValueError`.
- Fully masked queries contribute nothing. If every query is empty, the loss is `0.0` and the gradient is all zeros.
- Values in masked slots are arbitrary (for example `±1e6`) and must not affect results. Gradients at masked slots are `0`.
- Scores and relevance may reach a magnitude of about 1000. Loss and gradient must stay finite.
### What a Strong Answer Covers
- A masked log-softmax that shifts by the max over valid entries only, so large inputs stay finite and padded values never enter the computation.
- Safe handling of fully masked rows, with no `-inf`, `NaN` or division by zero.
- The per-query gradient on valid slots, scaled by the number of non-empty queries, with zeros on padding.
- Validation of shapes and of the `reduction` argument, and a mean that counts only non-empty queries.
- Time and space cost of the vectorized implementation.
### Follow-up Questions
- How would you add a temperature to the target distribution, and does it change the form of the gradient?
- Why is the loss invariant to per-query shifts of the scores, and what does that imply for the scores the model learns?
- How does top-one ListNet differ from the full top-k permutation probability version?
Overview: Implement the ListNet top-one ranking loss and its gradient for a padded batch of queries with a boolean mask. It tests a numerically stable masked log-softmax, the softmax cross-entropy gradient, handling of empty queries, and input validation.