MSE-on-Sigmoid vs BCE Logit Gradients
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given binary labels `y` and logits `z`, implement `sigmoid`, the mean losses `mse_on_sigmoid_loss` (mean of $(\sigma(z) - y)^2$) and `bce_with_logits_loss` (mean binary cross-entropy from logits), and their gradients with respect to `z`, `mse_on_sigmoid_grad` and `bce_with_logits_grad`. Every loss and gradient function takes `(y, z)`. Losses return a Python `float`. Gradients return an array shaped like `z` and include the ${1/n}$ factor from the mean (n = `z.size`).
For example:
```python
y = [1.0, 0.0, 1.0, 0.0]
z = [-1000.0, 1000.0, 1000.0, -1000.0]
bce_with_logits_loss(y, z) # 500.0
mse_on_sigmoid_loss(y, z) # 0.5
bce_with_logits_grad(y, z) # [-0.25, 0.25, 0.0, 0.0]
mse_on_sigmoid_grad(y, z) # [0.0, 0.0, 0.0, 0.0] saturated
```
```hint Stability
At z = ±1000, `exp(z)` overflows and `log(sigmoid(z))` can reach `log(0)`. Look for forms of the sigmoid and of the cross-entropy that only ever exponentiate a non-positive number.
```
```hint Gradients
Write each loss as a function of p = σ(z) and apply the chain rule. Compare which factors are left in each gradient when p is close to 0 or 1.
```
### Constraints & Assumptions
- `y` and `z` are 1-D array-likes of equal length, at least 1. Labels are 0 or 1.
- `|z|` may reach 1000, and every output must be finite (no overflow, no `log(0)`).
- `sigmoid(z) + sigmoid(-z) == 1` to within 1e-12, and `sigmoid(0) == 0.5`.
- Gradients must match central finite differences of the corresponding loss.
### What a Strong Answer Covers
- A sigmoid that never overflows and passes the symmetry and midpoint checks.
- A BCE loss computed directly from the logits in a stable form, never through `log(p)`.
- Chain-rule gradients for both losses with the mean's ${1/n}$ factor, consistent with finite differences.
- Why the MSE gradient saturates on confidently wrong predictions while the BCE gradient does not.
### Follow-up Questions
- Why does the MSE gradient vanish for confidently wrong predictions while BCE's does not?
- How does this extend to multiclass softmax with cross-entropy?
- Is each loss convex in z, and what does that mean for training logistic regression?
Overview: Implement a stable sigmoid, mean squared error on sigmoid outputs, and binary cross-entropy from logits, with gradients that match finite differences for logits as large as 1000. It tests numerical stability, the chain rule, and why MSE gradients saturate on confidently wrong predictions.