Heteroscedastic Gaussian NLL with Clamped Log-Variance
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `gaussian_nll` and `gaussian_nll_grad`. Given targets `y`, predicted means `mu` and log-variances `log_var`, compute the per-sample loss below with `s = clip(log_var, log_var_min, log_var_max)`, then reduce it. The gradient function returns `(g_mu, g_log_var)` of the reduced loss.
```python
per_i = 0.5 * (s_i + (y_i - mu_i)**2 * exp(-s_i)) + 0.5 * log(2*pi)
loss_i = w_i * per_i # w = ones if sample_weight is None
"none" -> array of loss_i
"sum" -> sum(loss_i)
"mean" -> sum(loss_i) / sum(w)
```
Use these signatures:
```python
def gaussian_nll(y, mu, log_var, sample_weight=None, reduction="mean",
log_var_min=-10.0, log_var_max=10.0): ...
def gaussian_nll_grad(y, mu, log_var, sample_weight=None, reduction="mean",
log_var_min=-10.0, log_var_max=10.0): ...
```
For example:
```python
y = [1.0, 2.0, -1.0]
mu = [0.0, 2.0, 1.0]
log_var = [0.0, np.log(4), np.log(0.5)]
gaussian_nll(y, mu, log_var, reduction="none") # [1.418939, 1.612086, 4.572365]
gaussian_nll(y, mu, log_var) # 2.534463
```
```hint Stay in log-variance space
Write the squared-error term as a product with a precision computed from the clamped log-variance, so no step ever divides by a variance.
```
```hint The clamp in the chain rule
Work out the derivative of clip(x, a, b) inside and outside the bounds, then decide which of the two gradients actually passes through it.
```
### Constraints & Assumptions
- `y`, `mu`, `log_var` (and `sample_weight` if given) must share a shape, else raise `ValueError`.
- `"mean"` and `"sum"` return a Python `float`. Any other reduction raises `ValueError` (the gradient also rejects `"none"`).
- `g_log_var` is `0` where `log_var` lies strictly outside `[log_var_min, log_var_max]`. `g_mu` always uses the clamped `s`.
- Outputs must stay finite for extreme `log_var` (for example `±1000`). Weights are positive.
### What a Strong Answer Covers
- A loss computed in log-variance space, with the clamp applied before any exponential so extreme inputs stay finite.
- Weighted reductions where the mean divides by `sum(w)`, plus the shape and reduction checks.
- Correct derivatives with respect to `mu` and `log_var`, and how the clamp affects each one.
- A way to confirm the gradients, such as finite differences.
- Time and space cost.
### Follow-up Questions
- Why predict log-variance instead of variance or standard deviation directly?
- What is the drawback of zeroing the gradient outside the clamp range, and how could you fix it?
- High-variance points get downweighted and the mean can fit poorly. How would you mitigate this?
Overview: Implement a weighted heteroscedastic Gaussian negative log-likelihood in NumPy, with a clamped log-variance and analytic gradients for the mean and log-variance. Tests numerical stability in log-variance space, weighted reductions, and how a clamp changes the chain rule.