Implement a hybrid soft Dice and BCE segmentation loss with analytic gradients
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `soft_dice_loss`, `soft_dice_grad`, `bce_with_logits`, `hybrid_loss` and `hybrid_grad` in NumPy. Inputs are batches of binary masks `y_true` with probabilities or logits of the same shape (axis 0 is the sample axis). Losses return a Python `float`, and gradients return arrays shaped like the input they differentiate.
```python
soft_dice_loss(y_true, y_prob, smooth=1.0)
soft_dice_grad(y_true, y_prob, smooth=1.0)
bce_with_logits(y_true, logits)
hybrid_loss(y_true, logits, alpha=0.5, smooth=1.0)
hybrid_grad(y_true, logits, alpha=0.5, smooth=1.0)
```
The functions must meet these requirements:
- Dice is computed per sample, with all non-batch axes flattened: `dice = (2·Σ(p·t) + smooth) / (Σp + Σt + smooth)`. The loss is the mean of `1 - dice` over samples.
- `bce_with_logits` is the mean over all elements and must be numerically stable for any logit magnitude.
- `hybrid_loss = alpha·BCE(logits) + (1 - alpha)·Dice(sigmoid(logits), smooth)`.
- `soft_dice_grad` is the gradient with respect to `y_prob`, and `hybrid_grad` is the gradient with respect to `logits`. Both are exact analytic gradients.
- Logits of ±1000 must give finite losses and gradients.
For example:
```python
y = [[[1,0],[1,0]], [[0,0],[0,0]]]
p = [[[.8,.2],[.6,.4]], [[.1,.1],[.1,.1]]]
soft_dice_loss(y, p) # (0.24 + (1 - 1/1.4)) / 2 ≈ 0.262857
y = [[1., 0.]]; z = [[-1000., 1000.]]
bce_with_logits(y, z) # 1000.0
hybrid_loss(y, z, alpha=0.5) # 500 + 1/3
hybrid_grad(y, z, alpha=0.5) # [[-0.25, 0.25]]
```
```hint Differentiating the Dice ratio
Each sample's Dice score is a ratio, and both its numerator and its denominator depend on every probability in that sample. Apply the quotient rule to a single element, then account for the mean over samples.
```
```hint Stay in logit space
For the BCE term and the sigmoid, find forms that never call `exp` on a large positive number. Then the gradient through the sigmoid is one application of the chain rule.
```
### Constraints & Assumptions
- Arrays have ndim ≥ 2 and matching shapes, and `y_true` values are 0 or 1.
- `0 ≤ alpha ≤ 1` and `smooth > 0`.
- Probabilities lie in [0, 1].
### What a Strong Answer Covers
- Per-sample Dice on flattened masks, averaged over the batch, and what `smooth` does for empty masks.
- A BCE-from-logits formula and a sigmoid that stay finite and accurate for logits of ±1000.
- The analytic Dice gradient from the quotient rule, including the factor from the batch mean.
- The hybrid gradient through the sigmoid, with the right normalization for each of the two terms.
- Return types and shapes, a check against the examples, and the linear time cost.
### Follow-up Questions
- Why compute Dice per sample instead of over the whole batch?
- How would you extend this to multi-class segmentation?
- Why combine BCE with Dice instead of using Dice alone?
Overview: Implement a segmentation loss that mixes per-sample soft Dice with binary cross-entropy from logits, along with its exact gradients in NumPy. It tests the quotient and chain rules, numerically stable logit math, and how losses are normalized over samples and pixels.