Numerically Stable Focal Loss from Raw Scores
Math & Bit ManipulationAuto-graded · 24 test casesLast updated
Implement a class-weighted, focus-modulated binary cross-entropy directly from logits in pure Python, with stable math, input validation and sum/mean/none reductions.
Stable Focal Loss
When positives are very rare, a plain binary cross-entropy is dominated by the huge number of easy negatives. Focal loss counters this by scaling each example's cross-entropy by two factors: a class weight and a "difficulty" factor that shrinks toward zero for examples the model already gets right.
Write a function that computes this loss from raw scores (logits) using plain Python lists. Do not build the loss by computing a probability and then taking its logarithm, because that breaks for extreme scores such as -1000 or 1000.
Definition
For a score z and a label y in {0, 1}:
p = 1 / (1 + exp(-z))p_t = pify == 1, otherwise1 - p- Class weight
w_t:- if
alpha == -1, thenw_t = 1for every example (weighting disabled); - otherwise
w_t = alphawheny == 1andw_t = 1 - alphawheny == 0.
- if
- Per-example loss:
w_t * (1 - p_t)^gamma * (-log(p_t))
When gamma == 0, the difficulty factor is exactly 1, and the loss is just weighted cross-entropy.
Task
Implement the function with the signature given in the starter code. Parameters:
scores: list of raw logits (floats or ints).labels: list of the same length containing0/1(ints or floats).alpha: positive-class weight, or the sentinel-1to disable class weighting.gamma: non-negative focusing exponent.reduction: one of"none","sum","mean".
Output
"none": a list of per-example losses, in input order."sum": a single float, the sum of the per-example losses."mean": a single float, the sum divided by the number of examples. For empty input, return0.0.
Validation
Raise ValueError if:
scoresandlabelshave different lengths;reductionis not one of the three allowed strings;gamma < 0;- any label is not
0or1.
Numerical requirements
- Results must be finite for any finite score, including magnitudes in the hundreds or thousands. Never exponentiate a large positive number.
- Use an accurately rounded summation (for example
math.fsum) when adding up losses.
Constraints
0 <= len(scores) <= 10^6scores[i]is a finite real number of any magnitude (e.g.|z|up to10^4)labels[i]is0,1,0.0or1.0gamma >= 0alphais either-1or a real number (typically in[0, 1])
Examples
Example 1
Input: stable_focal_loss([0, 2, -2], [1, 1, 0], 0.25, 2, 'mean')
Output: 0.01504175387341232
Example 2
Input: stable_focal_loss([-1000, 1000], [0, 1], 0.5, 2, 'none')
Output: [0, 0]
Example 3
Input: stable_focal_loss([0], [1], 0.25, 0, 'mean')
Output: 0.17328679513998632
Example 4
Input: stable_focal_loss([0, 2, -2], [1, 1, 0], -1, 0, 'mean')
Output: 0.31566773421529676
Hints
Hint 1
The negative log of p_t equals the cross-entropy, which can be written as max(z, 0) - z*y + log1p(exp(-|z|)). The exponent is never positive, so it cannot overflow.
Hint 2
Since 1 - sigmoid(z) = sigmoid(-z), the difficulty base 1 - p_t is sigmoid(-z) for positive labels and sigmoid(z) for negative labels. Evaluate sigmoid with two branches so that exp only ever sees a non-positive argument.
Hint 3
Handle the special cases explicitly: alpha == -1 gives weight 1, gamma == 0 gives factor 1, and an empty list under 'mean' returns 0.0. Validate inputs before computing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The loss for one example is w_t * (1 - p_t)^gamma * (-log p_t). The term -log p_t is just binary cross-entropy (BCE), so the task splits into three pieces, each computed stably.
-
Cross-entropy from the logit. Instead of taking
log(sigmoid(z)), useBCE(z, y) = max(z, 0) - z*y + log1p(exp(-|z|)). The exponent-|z|is never positive, soexpcannot overflow, andlog1pkeeps precision whenexp(-|z|)is tiny. -
Difficulty base
1 - p_t. Because1 - sigmoid(z) = sigmoid(-z), the base issigmoid(-z)for positive labels andsigmoid(z)for negative labels. Call that argumentx. Evaluatesigmoid(x)with two branches:- for
x >= 0:1 / (1 + exp(-x)); - for
x < 0:exp(x) / (1 + exp(x)).
Each branch only exponentiates a non-positive number. Arguments with magnitude of 746 or more are treated as underflowing to
0. Raising the base togammagives the difficulty factor; forgamma == 0it is set to1directly. - for
-
Class weight.
alphafor positives,1 - alphafor negatives, or1for everyone whenalpha == -1.
Multiply the three pieces per example, then apply the reduction. math.fsum gives an accurately rounded sum, and an empty list under "mean" returns 0.0.
Why it is correct
- For
y = 1,-log(sigmoid(z)) = log(1 + e^{-z}); fory = 0,-log(1 - sigmoid(z)) = log(1 + e^{z}). Both equalmax(z, 0) - z*y + log(1 + e^{-|z|}), as you can check by splitting on the sign ofz. - The two-branch sigmoid is algebraically identical to the textbook formula but never overflows.
- With
gamma = 0andalpha = -1, the weights are all1, leaving plain BCE. - For extreme scores such as
z = -1000, y = 0, BCE is0and the base is0, so the loss is exactly0.0with no NaN or infinity.
Complexity
- Time: O(n), constant work per example.
- Space: O(n) for the per-example losses (needed anyway for
"none").
Reference solution
import math
from typing import List, Union
def stable_focal_loss(scores: List[float], labels: List[float], alpha: float = 0.25, gamma: float = 2.0, reduction: str = 'mean') -> Union[List[float], float]:
if len(scores) != len(labels):
raise ValueError('scores and labels must have the same length')
if reduction not in ('none', 'mean', 'sum'):
raise ValueError('invalid reduction')
if gamma < 0:
raise ValueError('gamma must be nonnegative')
losses = []
for z, y in zip(scores, labels):
if y not in (0, 0.0, 1, 1.0):
raise ValueError('labels must be binary')
# Stable cross-entropy from logits.
bce = max(z, 0.0) - z * y + math.log1p(math.exp(-abs(z)))
if alpha == -1:
w = 1.0
else:
w = alpha if y == 1 else 1.0 - alpha
if gamma == 0:
factor = 1.0
else:
# 1 - p_t = sigmoid(-z) for positives, sigmoid(z) for negatives.
x = -z if y == 1 else z
if x >= 0:
e = math.exp(-x) if x < 746 else 0.0
base = 1.0 / (1.0 + e)
else:
e = math.exp(x) if x > -746 else 0.0
base = e / (1.0 + e)
factor = base ** gamma
losses.append(w * factor * bce)
if reduction == 'none':
return losses
if reduction == 'sum':
return math.fsum(losses)
return math.fsum(losses) / len(losses) if losses else 0.0