229. Cross-entropy with label smoothing from raw logits
Label smoothing stops a classifier from pushing its logits to extreme values. The one-hot target is mixed with a uniform distribution, so the model is never asked for probability exactly 1.
Write label_smoothed_ce(logits, targets, eps) where logits is (n, C), targets is a length-n list of class ids and 0 <= eps < 1.
- The smoothed target for row i is q = (1 - eps) * one_hot(targets[i]) + eps / C on every class (including the true class).
- Loss for a row is -sum_c q[c] * log_softmax(logits[i])[c].
- Return the mean over rows as a float.
Use a stable log-softmax so logits like 1000 work.
def label_smoothed_ce(logits, targets, eps)Example 1
Input: logits [[0, 0]], targets [0], eps 0.2
Output: log 2 = 0.693147..
Explanation: Because the prediction is already uniform.
Example 2
Input: logits = [[1000.0, 0.0, -1000.0]], targets = [0], eps = 0.3
Output: 300
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
log_softmax = z - max(z) - log(sum(exp(z - max(z)))).
Hint 2
Build q with np.full((n, C), eps / C) and add 1 - eps at the target columns.
Common mistakes
- The buggy version spreads eps / (C - 1) over the wrong classes and puts exactly 1 - eps on the true class.
Understand the idea
Label smoothing tells the model the right answer is very likely, not certain. The one-hot target is blended with a uniform spread, so the model stops pushing logits to extreme values. In this problem eps is spread over all C classes, including the true one.
C = 2, eps = 0.2, true class 0. q = (1 - 0.2) * [1, 0] + 0.2 / 2 = [0.9, 0.1]. Logits [2, 0]: logsumexp = log(e^2 + 1) = 2.1269, so log-probs are [-0.1269, -2.1269]. Loss = 0.9 * 0.1269 + 0.1 * 2.1269 = 0.1142 + 0.2127 = 0.3269.
q = (1 - eps) * one_hot + eps / C, row loss = -sum over classes of q times log_softmax(logits), then average rows
Compute log_softmax as logits minus their max, minus log of the summed exps, so logits like 1000 stay finite. Used when training image classifiers and many transformer models, often with eps = 0.1.
Topics
Companies2
- DeepMind the topic appears in interview reports Google DeepMind Onsite Interview: Every Round, What It Tests (SpaceComplexity)
- OpenAI a candidate reported this question AI interviews stopped asking 'what is a transformer'; now they hand you a broken one (Medium)
From public interview reports and guides. Not affiliated with or endorsed by these companies.