19. 计算永不溢出的 masked logsumexp
Log-likelihoods、CTC 和 attention 都需要在条目的子集上计算 log(sum(exp(x)))。较大的分数会导致 exp 溢出,且被 mask 的条目不应计入。
为形状相同的 2D 数组编写 masked_logsumexp(x, mask)。返回一个 1D float 数组,每行一个值:即 x 在 mask 为 true 的条目上的 logsumexp。没有 true 条目的行返回 -inf。在进行指数运算前,先减去保留条目的行最大值。
def masked_logsumexp(x, mask)示例 1
输入: x [[1000, 1000, 5]], mask [[1, 1, 0]]
输出: [1000 + log 2]
示例 2
输入: x = [[0.5, -1.0, 2.0], [3.0, 3.0, 3.0]], mask = [[1, 0, 1], [1, 1, 1]]
输出: [2.201413, 4.098612]
示例 3
输入: x = [[1.0, 2.0]], mask = [[0, 0]]
输出: [float('-inf')]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Masked entries should act as if they were never there, and -inf does exactly that because exp(-inf) is 0.
提示 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.
提示 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).
常见错误
- 有 Bug 的版本将被 mask 的条目设置为 0,而 exp(0) = 1 会悄悄增加不该存在的权重。
理解思路
logsumexp 计算 log(sum(exp(x))),这是用于 log-likelihoods、CTC 和 attention 的 soft maximum。大数字的 exp 会溢出,因此先减去最大值,之后再加回来,这在数学上没有变化。配合 mask 使用时,只有保留的条目应当被计入。
x = [[2, 3, 100]], mask = [[1, 1, 0]]。保留的条目:2 和 3,max 为 3。log(exp(2 - 3) + exp(3 - 3)) = log(0.3679 + 1) = 0.3133,加上 3 得到 3.3133。被 mask 的 100 必须不产生影响。没有保留条目的行返回 -inf。
将被 mask 的条目设置为 -inf,这样 exp 会将其变为精确的零;m = 保留条目的行最大值;result = 每行 m + log(sum(exp(x - m)));单独处理全被 mask 的行,以免计算 -inf 减去 -inf。如果错误地将被 mask 的条目设置为 0,exp(0) = 1 会增加不应存在的权重。该技术用于 sequence losses 中的 padded batches 和 masked attention normalisers。
公司1
- Apple a candidate reported this question Apple Machine Learning Engineer Interview | Screna AI
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。