BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / NumPy foundations19 of 23 in topic

19. Compute a masked logsumexp that never overflows

MediumNumPy foundations
Asked atApple

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.

Functiondef 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.

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.

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
NumPy foundations
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.

Similar questions
  • Average only the real tokens in a padded batchMedium
  • Cut a token sequence into overlapping fixed-size windowsMedium
  • Answer many range-sum queries in constant time with prefix sumsMedium
  • Assign sequences to length buckets with searchsorted and count paddingMedium
All NumPy foundations problems
Report
19 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def masked_logsumexp(x, mask):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS