Focal Loss From Logits With Gradients
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement focal loss from raw logits:
$$FL = -\alpha_t \, (1 - p_t)^{\gamma} \, \log p_t$$
where $p_t$ is the predicted probability of the true class. Implement `binary_focal_loss` (sigmoid, logits of shape `(n,)`) and `softmax_focal_loss` (softmax, logits of shape `(n, k)`), plus `binary_focal_loss_grad` and `softmax_focal_loss_grad`, which return the gradient of the mean loss with respect to the logits (same shape as `logits`).
The functions take labels first, then logits:
```python
def binary_focal_loss(y_true, logits, gamma=2.0, alpha=0.25, reduction="mean"): ...
def binary_focal_loss_grad(y_true, logits, gamma=2.0, alpha=0.25): ...
def softmax_focal_loss(y_true, logits, gamma=2.0, alpha=None, reduction="mean"): ...
def softmax_focal_loss_grad(y_true, logits, gamma=2.0, alpha=None): ...
```
For example:
```python
binary_focal_loss([1, 0], [0.0, 0.0], gamma=2.0, alpha=0.25, reduction="none")
# -> [0.0625*ln2, 0.1875*ln2] ≈ [0.04332, 0.12997]
binary_focal_loss([1, 0], [0.0, 0.0], gamma=2.0, alpha=0.25)
# -> 0.125*ln2 ≈ 0.08664
```
```hint Stable log-probabilities
Never take the log of a probability you already computed. Get log p_t straight from the logits with a log-sigmoid or a max-shifted log-softmax, and derive 1 - p_t from log p_t too.
```
```hint Gradient through log p_t
Write the loss as a function of log p_t. Its derivative with respect to the logits is short for both sigmoid and softmax, and the derivative of 1 - p_t follows from it.
```
```hint Tests that catch bugs
Compare against finite differences, check that gamma = 0 with alpha=None gives plain cross-entropy, and try a sample whose true-class logit sits far above the others.
```
### Constraints & Assumptions
- Binary: `alpha_t = alpha` if `y == 1`, else `1 - alpha`. Softmax: `alpha` is a per-class array indexed by label. `alpha=None` means `alpha_t = 1`.
- `reduction`: `"mean"` and `"sum"` return a `float`, `"none"` returns the per-sample array, anything else raises `ValueError`.
- Logits may reach `±1000`. Losses and gradients must stay finite and exact (for example `y=1, z=-1000, alpha=0.25` gives `250.0`).
- `gamma ≥ 0`. With `gamma=0, alpha=None` the loss equals cross-entropy. Gradients must match finite differences for `gamma` in `{0.5, 2.0}`.
- Binary labels are 0/1. Multi-class labels are ints in `[0, k)`. The softmax loss must be invariant to adding a constant to all logits.
### What a Strong Answer Covers
- How `log p_t` and `1 - p_t` are computed from the logits so that logits of `±1000` give finite, exact losses.
- Correct `alpha_t` for the binary case, the per-class case and `alpha=None`, and the full `reduction` contract including the error case.
- A chain-rule derivation of the gradient of the mean loss for both heads, checked against finite differences.
- Behavior at the edges: perfectly classified samples, `gamma = 0`, and shift invariance of the softmax.
- The cost in terms of samples and classes.
### Follow-up Questions
- What goes wrong in the softmax gradient when `gamma < 1` and a sample is perfectly classified?
- How would you verify that the binary loss is a special case of the multi-class one?
- How do focal loss and class-weighted cross-entropy differ under class imbalance?
Overview: Implement binary and softmax focal loss directly from raw logits, along with the gradient of the mean loss with respect to the logits. Tests numerically stable log-space computation, alpha weighting and reduction handling, and a chain-rule derivation checked against finite differences.