Attention 的计算公式中为什么要除以根号k ?这么回答惊艳面试官!
回答:1. 保证梯度稳定;2.保持attention score为均值0方差1的分布,这样便于后续的优化。
详解:1. QK乘积可能会存在较大的值,这些值如果比较大,会导致算softmax的时候算出来的结果趋向于极值,也就是softmax的概率分布趋向于最大值对应的标签,从矩阵上看就这个最大值对应的位置有梯度,其它地方没梯度,导致反向传播的梯度不稳定。
2.上面的公式给出了不除以d**0.5的话,会导致方差变大,为了保持方差的问题,需要除一下。
最基本的答案
这个问题在《Attention is All You 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