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

856. Fix the softmax that returns nan

EasyDebug and fix

Why it matters Overflow in softmax is the most common numerical bug in ML code, and the fix is asked in almost every ML coding interview.

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.

softmax_rows(x) should return the softmax of each row of a 2D array.

Inputs: x is a list or ndarray of shape (n, k). Values can be very large or very negative (for example 1000.0 or -1000.0).

Return an ndarray of floats with shape (n, k), every row summing to 1, with no nan or inf values. No rounding.

Functiondef softmax_rows(x)

Example 1

Input: softmax_rows([[1.0, 2.0, 3.0]])

Output: [[0.09, 0.2447, 0.6652]]

Example 2

Input: x = [[1000.0, 1001.0]]

Output: [[0.268941, 0.731059]]

Example 3

Input: x = [[0.0, 0.0], [800.0, 0.0]]

Output: [[0.5, 0.5], [1.0, 0.0]]

Constraints

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

Try the large logits test by hand: what is np.exp(1000.0)?

Hint 2

Softmax is shift invariant per row.

Hint 3

Subtract x.max(axis=1, keepdims=True) before exp.

Common mistakes
  • Subtracting the global max instead of the row max (works but hides intent and can underflow other rows).
  • Clipping inputs, which changes the answer.
  • Forgetting keepdims, which breaks broadcasting.
Understand the idea

exp(1000) overflows to inf, and inf / inf is nan. Softmax does not change if you subtract the same number from every entry of a row, so subtract the row maximum first. Then the largest exponent is exp(0) = 1 and nothing overflows. exp(-1000) underflows to 0 for every entry of a very negative row, which gives 0 / 0; the shift fixes that too.

Shapes and data flow
x: (n, k). The max is taken per row with keepdims=True.
Topics
Debug and fix
Similar questions
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the F1 score that crashes on empty predictionsEasy
  • Fix the agent memory shared between conversationsEasy
All Debug and fix problems
Report
856 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
import numpy as np
​
def softmax_rows(x):
x = np.asarray(x, dtype=float)
e = np.exp(x)
return e / e.sum(axis=1, keepdims=True)
​

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

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