19. Compute a masked logsumexp that never overflows
Log-likelihoods, CTC and attention all need log(sum(exp(x))) over a subset of entries. Large scores overflow exp, and masked entries must not count.
Write masked_logsumexp(x, mask) for 2D arrays of the same shape. Return a 1D float array with one value per row: the logsumexp of x over entries where mask is true. Rows with no true entries return -inf. Subtract the row max of the kept entries before exponentiating.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def masked_logsumexp(x, mask)Example 1
Input: x [[1000, 1000, 5]], mask [[1, 1, 0]]
Output: [1000 + log 2]
Example 2
Input: x = [[0.5, -1.0, 2.0], [3.0, 3.0, 3.0]], mask = [[1, 0, 1], [1, 1, 1]]
Output: [2.201413, 4.098612]
Example 3
Input: x = [[1.0, 2.0]], mask = [[0, 0]]
Output: [float('-inf')]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Masked entries should act as if they were never there, and -inf does exactly that because exp(-inf) is 0.
Hint 2
Use np.where(mask, x, -np.inf), take the max of each row, subtract it before np.exp, sum along the row, then take np.log and add the max back.
Hint 3
A row with no true entries has max -inf, and -inf - -inf is NaN, so swap such maxes for 0 while computing and then set those rows to -inf at the end using ~mask.any(axis=1).
Common mistakes
- The buggy version sets masked entries to 0, and exp(0) = 1 quietly adds mass that should not be there.
Understand the idea
logsumexp computes log(sum(exp(x))), the soft maximum used in log-likelihoods, CTC and attention. exp of large numbers overflows, so you subtract the largest value first and add it back after, which changes nothing mathematically. With a mask, only the kept entries should count.
x = [[2, 3, 100]], mask = [[1, 1, 0]]. Kept entries: 2 and 3, max 3. log(exp(2 - 3) + exp(3 - 3)) = log(0.3679 + 1) = 0.3133, plus 3 gives 3.3133. The masked 100 must have no effect. A row with no kept entries returns -inf.
set masked entries to -inf so exp turns them into exact zeros; m = row max over kept entries; result = m + log(sum(exp(x - m))) per row; handle all-masked rows separately so you do not compute -inf minus -inf
Setting masked entries to 0 instead is wrong because exp(0) = 1 adds mass. Used for padded batches in sequence losses and masked attention normalisers.
Topics
Companies1
- Apple a candidate reported this question Apple Machine Learning Engineer Interview | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.