题目
Attention 的计算公式中 为什么要除以根号d ?
这个题目可以说是 NLP 面试中一个高频出现的问题,基本上问到 Attention 或者 Transformers 的时候都会问。
这是个好题目,我作为面试官的时候也经常问,因为很快能了解到面试同学的数学功底怎么样。
基本答案
这个问题在《Attention is All Your Need》的原始论文中是给出了一个粗略的答案的。
While for small values of the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of [3]. We suspect that for large values of, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients . To counteract this effect, we scale the dot products by .
作者说,当 的值变大的时候,softmax 函数会造成梯度消失问题,所以设置了一个 softmax 的 temperature 来缓解这个问题。这里 temperature 被设置为了 , 也就是乘上 .
这个回答当然没什么问题,但是接下来就会再问两个问题:
- 为什么会导致梯度消失?
- 为什么是 , 有更好的值么?
下面来回答一下这两个衍生的问题
dk变大为什么会导致梯度消失?
先说结论:
- 如果 dk 变大,q·K 方差会变大。
- 方差变大会导致向量之间元素的差值变大。
- 元素的差值变大会导致 softmax 退化为argmax, 也就是最大值 softmax 后的值为 1, 其他值则为0。
- softmax 只有一个值为 1 的元素,其他都为 0的话,反向传播的梯度会变为 0, 也就是所谓的梯度消失。
下面分别证明这 4 点。