Log-softmaxEasynumpysoftmaxnumerical-stabilitylossfundamentals
Log-softmax
Background
Log-softmax computes in a numerically stable way. It appears everywhere softmax and log show up together — cross-entropy loss, log-likelihoods, beam search — because computing them jointly avoids the overflow of exp on large logits and the underflow on tiny probabilities.
Problem statement
Implement log_softmax(x) over the last axis:
The max-subtraction is the stability trick; it cancels mathematically but prevents overflow.
Input
x—np.ndarray: 1-D logits, or 2-D(batch, classes)(softmax taken over the last axis).
Output
Returns an np.ndarray of the same shape: the log-probabilities (each row's exp sums to 1).
Examples
Example 1
Input: x = [1, 2, 3]
Output: [-2.4076, -1.4076, -0.4076]
Explanation: subtract the max () to get , then subtract .
Constraints
- Subtract the per-row max before exponentiating (numerical stability).
- Operate over the last axis; support both 1-D and 2-D inputs.
exp(log_softmax(x))must sum to 1 along the last axis; tests useatol=1e-6.
Notes
- ; never compute
log(softmax(x))as two separate steps — the intermediate softmax can underflow to 0. - Cross-entropy loss is just , which is why frameworks fuse the two operations.
Python
Loading...
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example
- •exp(log_softmax) sums to 1
- •Matches log of a stable softmax
- •Numerically stable for large logits (no overflow)
- •Row-wise for 2-D input