BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges6 of 14 in topic

877. Batched softmax without the row loop

EasyOptimization challenges

Why it matters Row loops over a batch are the most common slow pattern in model code ported from single-example logic.

batch_softmax(x) returns a numerically stable softmax over the last axis of a 2D array (subtract each row's max before exp).

Inputs: x is a list or ndarray of shape (n, k).

Return an ndarray of floats with shape (n, k). No rounding.

The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 25 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.

Functiondef batch_softmax(x)

Example 1

Input: batch_softmax([[0.0, 1.0], [2.0, 2.0]])

Output: [[0.2689, 0.7311], [0.5, 0.5]]

Example 2

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

Output: [[0.5, 0.0, 0.5]]

Example 3

Input: x = [[5.0]]

Output: [[1.0]]

Constraints

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

Reduce with axis=1, keepdims=True.

Hint 2

Subtract, exp, divide: three array operations.

Hint 3

No Python loop needed.

Common mistakes
  • Global max instead of row max (still stable, but slower to reason about).
  • Dropping keepdims and broadcasting along the wrong axis.
  • Using np.vectorize, which is still a Python loop.
Understand the idea

Every NumPy reduction takes an axis. Using axis=1 with keepdims=True keeps the shape (n, 1) so it broadcasts back over the row. One exp over the whole (n, k) array replaces n small calls, each with its own overhead.

Shapes and data flow
x: (n, k). max and sum: (n, 1).
Topics
Optimization challenges
Similar questions
  • Rolling mean with a cumulative sumEasy
  • Count token frequencies fastEasy
  • Padding mask from sequence lengthsEasy
  • Confusion matrix in one passEasy
All Optimization challenges problems
Report
877 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def batch_softmax(x):
x = np.asarray(x, dtype=float)
out = np.empty_like(x)
for i in range(x.shape[0]):
e = np.exp(x[i] - x[i].max())
out[i] = e / e.sum()
return out
​

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

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