877. Batched softmax without the row loop
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.
def 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).