自注意力在 GPT 的计算里做了什么?
查看完整题解
参考回答
直接回答
自注意力让当前位置从允许看到的各位置收集信息。简单说,查询向量和各键向量算相关分数,经缩放与归一化得到权重,再用这些权重混合相应的值向量。
讲清原理
GPT 常用因果遮罩,让位置只读自己和更早的输入位置。不同注意力头可以学习对不同关系敏感。单看某一头的权重,也不能穷尽整条输出的成因。
例子与易错点
下面让第二个位置做一次小注意力计算。即使第三个位置的分数很高,遮罩也会把它挡住。
from math import exp, sqrt
query = (1.0, 1.0)
keys = [(1.0, 0.0), (1.0, 1.0), (100.0, 100.0)]
values = [1.0, 3.0, 1000.0]
position = 1 # Only positions 0 and 1 are visible.
scores = [sum(a * b for a, b in zip(query, key)) / sqrt(len(query))
for key in keys[:position + 1]]
mass = [exp(score - max(scores)) for score in scores]
weights = [value / sum(mass) for value in mass] + [0.0]
mixed = sum(weight * value for weight, value in zip(weights, values))
assert weights[2] == 0.0 and 1.0 < mixed < 3.0
print("the third position was masked, even with a much larger score")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。