self-attention部分代码注释
多头注意力机制(Multi-Head Attention, MHA),是 Transformer 模型的核心组件之一。以下是对代码的逐行解析和详细说明:
attention-is-all-you-need-pytorch-master\transformer\SubLayers.py
class MultiHeadAttention(nn.Module):
''' Multi-Head Attention module '''
'''
n_head: 多头注意力head数量 8
d_model: 输入向量的维度 512
d_k : 单head中 Q, k 向量的维度 512 / 8 = 64
d_v : 单head中V向量的维度 d_k, 与d_v是独立的,可以相等也可以不等。在这里d_k = d_v 64
'''
def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
super().__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
self.fc = nn.Linear(n_head * d_v, d_model, bias=False)
self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
def forward(self, q, k, v, mask=None):
'''
q, k, v 的形状为 (32, 10, 512)(batch_size=32,seq_len=10,d_model=512)
'''
d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
residual = q
# Pass through the pre-attention projection: b x lq x (n*dv)
# Separate different heads: b x lq x n x dv
q = self.w_qs(q).view(sz_b, len_q, n_head, d_k) #view 为多头
k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
# Transpose for attention dot product: b x n x lq x dv
#q, k, w的维度为(32, 10, 8, 64) 转换后维度为(32, 8, 10, 64)
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
if mask is not None:
mask = mask.unsqueeze(1) # For head axis broadcasting.
'''
attn: (32, 8, 10, 10)
输出q: (32, 8, 10, 64)
'''
q, attn = self.attention(q, k, v, mask=mask)
# Transpose to move the head dimension back: b x lq x n x dv
# Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)
q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1) #(32, 10, 512)
q = self.dropout(self.fc(q))
q += residual
q = self.layer_norm(q)
return q, attn
attention-is-all-you-need-pytorch-master\transformer\Modules.py
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
def forward(self, q, k, v, mask=None):
'''
q: (32, 8, 10, 64) -> 缩放 -> (32, 8, 10, 64)
k: (32, 8, 10, 64) -> 转置 -> (32, 8, 64, 10)
attn = q @ k.transpose(2, 3): (32, 8, 10, 10)
attn: (32, 8, 10, 10) -> softmax -> (32, 8, 10, 10)
v: (32, 8, 10, 64)
output = attn @ v: (32, 8, 10, 64)
'''
attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
if mask is not None:
attn = attn.masked_fill(mask == 0, -1e9)
attn = self.dropout(F.softmax(attn, dim=-1))
output = torch.matmul(attn, v)
return output, attn