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.

Signaturedef masked_logsumexp(x, mask)

Example

x [[1000, 1000, 5]], mask [[1, 1, 0]] gives [1000 + log 2].

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. Worked example: 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. Rule: 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplemasked_logsumexp([[1000.0, 1000.0, 5.0]], [[1, 1, 0]])
  • Sample 2: randommasked_logsumexp([[0.5, -1.0, 2.0], [3.0, 3.0, 3.0]], [[1, 0, 1], [1, 1, 1]])
  • Test 3: empty rowmasked_logsumexp([[1.0, 2.0]], [[0, 0]])
  • Test 4: negative scalemasked_logsumexp([[-1000.0, -1001.0]], [[1, 1]])