平均汇聚注意力 生成数据集 简单起见,考虑下面这个回归问题:给定的成对的“输入-输出”数据集 ,如何学习 来预测任意新输入 的输出 ?根据下面的非线性函数生成一个人工数据集,其中加入的噪声项为 :
其中 服从均值为 和标准差为 的正态分布。在这里生成了 个训练样本和 个测试样本。为了更好地可视化之后的注意力模式,需要将训练样本进行排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def f (x ): return 2 * torch.sin(x) + x**0.8 n_train = 50 x_train, _ = torch.sort(torch.rand(n_train) * 5 ) y_train = f(x_train) + torch.normal(0.0 , 0.5 , (n_train,)) x_test = torch.arange(0 , 5 , 0.1 ) y_truth = f(x_test) n_test = len (x_test) print (f"训练样本数: {n_train} , 测试样本数: {n_test} " )
先使用最简单的估计器来解决回归问题。基于平均汇聚来计算所有训练样本输出值的平均值:
如下图所示,这个估计器确实不够聪明。真实函数 (“Truth”)和预测函数(“Pred”)相差很大。
1 2 3 4 y_hat = torch.repeat_interleave(y_train.mean(), n_test) plot([x_test, x_test, x_train],[y_hat,y_truth, y_train], legend=['Predicted' , 'Truth' , 'Training' ], x_name="x" ,y_name="y" , file_name="mean.png" ,line_styles=['-' , '-' , 'o' ])
非参数注意力汇聚 显然,平均汇聚忽略了输入 。于是 Nadaraya和Watson提出了一个更好的想法,根据输入的位置对输出 进行加权:
函数是核 (kernel)。上面公式所描述的估计器被称为 Nadaraya-Watson 核回归 (Nadaraya-Watson kernel regression)。其中, 对应查询, 对应被汇聚的各个项,也就是键, 用于计算加权的权重, 对应最终被加权求和的值;
我们可以从QKV图中的注意力机制框架的角度重写这个公式,使其成为一个更加通用的注意力汇聚 (attention pooling)公式:
其中 是查询, 是键值对。比较平均汇聚和这个公式,注意力汇聚是 的加权平均。将查询 和键 之间的关系建模为注意力权重 (attention weight) ,这个权重将被分配给键对应的值 。通过对各个注意力权重进行softmax操作,保证模型在所有键值对注意力权重都是一个有效的概率分布:它们是非负的,并且总和为 1。
为了更好地理解注意力汇聚,下面考虑一个高斯核 (Gaussian kernel),其定义为:
将高斯核代入NW核公式中可以得到如下式子,正好可以写成softmax形式;
值得注意的是,Nadaraya-Watson 核回归是一个非参数模型。上面的式子是非参数的注意力汇聚 (nonparametric attention pooling)模型。接下来,我们将基于这个模型来绘制预测结果。从绘制的结果会发现新的模型预测线是平滑的,并且比平均汇聚的预测更接近真实。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 X_repeat = x_test.repeat_interleave(n_train).reshape((-1 , n_train)) attention_weights = nn.functional.softmax(-(X_repeat - x_train)**2 / 2 , dim=1 ) y_hat = torch.matmul(attention_weights, y_train) plot([x_test, x_test, x_train],[y_hat,y_truth, y_train],legend=['Predicted' , 'Truth' , 'Training' ],x_name="x" ,y_name="y" , file_name="attention.png" , line_styles=['-' , '-' , 'o' ]) show_heatmaps(attention_weights.reshape((1 , 1 , n_test, n_train)), xlabel='Sorted training inputs' , ylabel='Sorted testing inputs' , filename="attention_heatmap.png" )
从绘制出的结果可以看到,预测值已经比较你和真实值了;
现在来观察注意力的权重。这里测试数据的输入相当于查询,而训练数据的输入相当于键。因为两个输入都是经过排序的,因此由观察可知“查询-键”对越接近,注意力汇聚的[注意力权重 ]就越高。
1 2 3 show_heatmaps(attention_weights.reshape((1 , 1 , n_test, n_train)), xlabel='Sorted training inputs' , ylabel='Sorted testing inputs' , filename="attention_heatmap.png" )
带参数的注意力汇聚 非参数的 Nadaraya-Watson 核回归具有一致性 (consistency)的优点:如果有足够的数据,此模型会收敛到最优结果。此外,我们还可以将可学习的参数集成到注意力汇聚中。
例如,与非参数注意力略有不同,在下面的查询 和键 之间的距离乘以可学习参数 :
本节的余下部分将通过训练这个模型来学习注意力汇聚的参数。
批量矩阵乘法 为了更有效地计算小批量数据的注意力,我们可以利用深度学习开发框架中提供的批量矩阵乘法。
假设第一个小批量数据包含 个矩阵 ,形状为 ,第二个小批量包含 个矩阵 ,形状为 。它们的批量矩阵乘法得到 个矩阵 ,形状为 。因此,假定两个张量的形状分别是 和 ,它们的批量矩阵乘法输出的形状为** **]。
1 2 3 X = torch.ones((2 , 1 , 4 )) Y = torch.ones((2 , 4 , 6 )) torch.bmm(X, Y).shape
在注意力机制的背景中,我们可以使用小批量矩阵乘法来计算小批量数据中的加权平均值。
1 2 3 4 5 6 7 weights = torch.ones((2 , 10 )) * 0.1 values = torch.arange(20.0 ).reshape((2 , 10 )) torch.bmm(weights.unsqueeze(1 ), values.unsqueeze(-1 ))
定义模型 基于带参数的注意力汇聚,使用小批量矩阵乘法,定义 Nadaraya-Watson 核回归的带参数版本为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class NWKernelRegression (nn.Module): def __init__ (self, **kwargs ): super ().__init__(**kwargs) self .w = nn.Parameter(torch.rand((1 ,), requires_grad=True )) def forward (self, queries, keys, values ): queries = queries.repeat_interleave(keys.shape[1 ]).reshape((-1 , keys.shape[1 ])) self .attention_weights = nn.functional.softmax( -((queries - keys) * self .w)**2 / 2 , dim=1 ) return torch.bmm(self .attention_weights.unsqueeze(1 ), values.unsqueeze(-1 )).reshape(-1 )
训练 接下来,将训练数据集变换为键和值用于训练注意力模型。在带参数的注意力汇聚模型中,任何一个训练样本的输入都会和除自己以外的所有训练样本的“键-值”对进行计算,从而得到其对应的预测输出。
1 2 3 4 5 6 7 8 9 10 X_tile = x_train.repeat((n_train, 1 )) Y_tile = y_train.repeat((n_train, 1 )) keys = X_tile[(1 - torch.eye(n_train)).type (torch.bool )].reshape((n_train, -1 )) values = Y_tile[(1 - torch.eye(n_train)).type (torch.bool )].reshape((n_train, -1 ))
训练带参数的注意力汇聚模型时,使用平方损失函数和随机梯度下降。
1 2 3 4 5 6 7 8 9 10 11 12 net = NWKernelRegression() loss = nn.MSELoss(reduction='none' ) trainer = torch.optim.SGD(net.parameters(), lr=0.5 ) animator = d2l.Animator(xlabel='epoch' , ylabel='loss' , xlim=[1 , 5 ]) for epoch in range (5 ): trainer.zero_grad() l = loss(net(x_train, keys, values), y_train) l.sum ().backward() trainer.step() print (f'epoch {epoch + 1 } , loss {float (l.sum ()):.6 f} ' ) animator.add(epoch + 1 , float (l.sum ()))
如下所示,训练完带参数的注意力汇聚模型后可以发现:在尝试拟合带噪声的训练数据时,预测结果绘制的线不如之前非参数模型的平滑。
与非参数的注意力汇聚模型相比,带参数的模型加入可学习的参数后,曲线在注意力权重较大的区域变得更不平滑。
1 2 3 show_heatmaps(net.attention_weights.unsqueeze(0 ).unsqueeze(0 ), xlabel='Sorted training inputs' , ylabel='Sorted training inputs' , filename="param_attention_heatmap.png" )