BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix5 of 16 in topic

860. Fix the cross-entropy that returns inf

EasyDebug and fix

Why it matters Taking log of a softmax is the textbook way to get inf losses. Frameworks fuse log_softmax for exactly this reason.

The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.

cross_entropy(logits, labels) should return the mean negative log likelihood of the correct class: mean over rows of -log_softmax(logits)[i, labels[i]]. Compute log_softmax with the log-sum-exp trick so extreme logits give a finite answer.

Inputs: logits is a list or ndarray of shape (n, k). labels is a list or ndarray of n ints in [0, k).

Return a Python float. No rounding.

Functiondef cross_entropy(logits, labels)

Example 1

Input: cross_entropy([[2.0, 0.0], [0.0, 2.0]], [0, 0])

Output: 1.1269

Example 2

Input: logits = [[0.0, 800.0]], labels = [0]

Output: 800.0

Example 3

Input: logits = [[1000.0, 0.0, 0.0], [0.0, 0.0, -900.0]], labels = [1, 2]

Output: 950.346574

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

Print p for the confident and wrong test. What is log of that?

Hint 2

log(exp(z) / S) = z - log(S).

Hint 3

Index the log probabilities, not the probabilities.

Common mistakes
  • Clipping p to 1e-12, which caps the loss at about 27.6 and gives the wrong value.
  • Summing instead of averaging over rows.
  • Using labels as one-hot when they are ints.
Understand the idea

After the max shift the softmax itself is safe, but a probability like exp(-800) underflows to 0.0, and log(0) is -inf. Staying in log space avoids it: log_softmax = z - logsumexp(z). For logits [0, 800] with label 0 the loss is exactly 800, not inf.

Shapes and data flow
logits: (n, k). labels: (n,). Output: scalar.
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the F1 score that crashes on empty predictionsEasy
  • Fix the agent memory shared between conversationsEasy
All Debug and fix problems
Report
860 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
import numpy as np
​
def cross_entropy(logits, labels):
z = np.asarray(logits, dtype=float)
y = np.asarray(labels)
z = z - z.max(axis=1, keepdims=True)
p = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
return float(-np.log(p[np.arange(len(y)), y]).mean())
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS