Implement a weighted Poisson negative log-likelihood loss and its gradient from log-rates
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `poisson_nll` and `poisson_nll_grad`. Given integer `counts` y and predicted `log_rate` η (rate λ = exp(η)), the per-example loss is the full negative log-likelihood `exp(η) - y·η + lgamma(y + 1)`. The gradient function returns d(loss)/dη with the same shape as `log_rate`.
Both functions take `(counts, log_rate, sample_weight=None, reduction="mean")` and follow these rules:
- `reduction="mean"` gives `Σ w·ℓ / Σ w`, `"sum"` gives `Σ w·ℓ`, and `"none"` gives the array `w·ℓ`. The weights `w` default to ones. Loss scalars are Python `float`.
- The gradient per element is `w·(exp(η) - y)`, divided by `Σ w` for `"mean"`. The gradient is always an array.
- When y = 0, the `y·η` term is exactly 0, so results stay finite for η as low as `-1000`.
- Raise `ValueError` for negative, non-integer or non-finite counts, NaN log-rates, shape mismatches, negative weights, or an unknown `reduction`.
For example:
```python
counts = [0, 2, 4]
log_rate = [0.0, log(2), 0.0]
poisson_nll_grad(counts, log_rate, reduction="none") # [1.0, 0.0, -3.0]
poisson_nll_grad(counts, log_rate) # [1/3, 0.0, -1.0]
poisson_nll([0], [-1000.0], reduction="none") # [0.0]
```
```hint Stay in log-rate space
Write every term directly in η. Look for the step that would produce `log(0)` or `0 * (-inf)` if you computed λ first and took its log.
```
```hint Weights and the mean
The weighted mean is a weighted sum divided by a constant that does not depend on η. Work out what that does to each element of the gradient.
```
### Constraints & Assumptions
- `counts`, `log_rate` and the optional `sample_weight` are array-like and must have the same shape.
- Computation is in float64.
- Log-rates can be as low as `-1000`, and the loss and gradient must stay finite there when the count is 0.
- Weights are non-negative and default to ones.
### What a Strong Answer Covers
- The loss computed from η directly, with the `y·η` term exactly 0 for zero counts.
- The `lgamma(y + 1)` term, so the values equal the full Poisson negative log-likelihood.
- Weighted `"mean"`, `"sum"` and `"none"` reductions for both functions, with Python `float` loss scalars and an array gradient in every mode.
- Validation that raises `ValueError` for each listed kind of bad input.
- Behavior at extreme log-rates and the linear time and space cost.
### Follow-up Questions
- Why parameterize by log-rate instead of the rate directly?
- How would you guard against overflow for large positive log-rates?
- When can the `lgamma(y + 1)` term be dropped?
Overview: Implement a weighted Poisson negative log-likelihood and its gradient with respect to log-rates, with mean, sum and per-example reductions. It tests numerically stable loss code for count data, the gradient of a log link, and careful input validation.