在 Transformer 模型中,self-attention 是如何计算的?
在 Transformer 模型中,self-attention 是通过以下步骤计算的:
- 输入数据(通常是词嵌入向量)经过三个线性变换(权重矩阵)得到查询(Q)、键(K)和值(V)的向量。
- 查询向量与键向量计算点积,并通过缩放操作得到注意力分数。
- 将注意力分数经过 softmax 函数和 V 向量相乘,得到自注意力的加权和。
- 这个加权和作为输出。
示例:
# Python 代码示例
import torch
import torch.nn.functional as F
# 输入数据
input_data = torch.randn(batch_size, sequence_length, embedding_dimension)
# 线性变换
Q = torch.matmul(input_data, W_q)
K = torch.matmul(input_data, W_k)
V = torch.matmul(input_data, W_v)
# 点积注意力
attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / sqrt(d_k)
attention_weights = F.softmax(attention_scores, dim=-1)
output = torch.matmul(attention_weights, V)