Frame · dsa / ai-algorithms / 17-stable-softmax-log-sum-exp.jsJavaScript
Numerically Stable Softmax and Log-Sum-Exp
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Numerically Stable Softmax and Log-Sum-Exp
Problem: Logits from a model can be large (hundreds or thousands), and a
naive `exp(x) / sum(exp(x))` overflows to Infinity / NaN. Implement:
- `logSumExp(xs)`: log(sum(exp(x))) computed stably; returns -Infinity
for an empty array or when every entry is -Infinity (fully masked).
- `softmax(xs, temperature = 1)`: probabilities that sum to 1.
- `logSoftmax(xs)`: x_i - logSumExp(xs), used for cross-entropy and beam
scores without ever forming tiny probabilities.
- `crossEntropy(logits, target)`: -logSoftmax(logits)[target].
Constraints:
- 1 <= xs.length <= 10^6, entries are finite or -Infinity (masked)
Example:
softmax([1000, 1001]) -> [0.2689..., 0.7310...] (naive version gives NaN)
logSumExp([0, 0]) -> ln 2
Approach: Shift by the maximum m: log(sum exp(x)) = m + log(sum exp(x - m)).
Every exponent is then <= 0, so nothing overflows and the largest term is
exactly 1, so the sum never underflows to 0. Time O(n), space O(n) for the
output (O(1) extra for logSumExp).
@param {number[]} xs
@returns {number}