關於transformer的原理,這裏就不多說,主要還是結合論文中的圖來對代碼進行一下講解。
看這張圖,其實可以看到最核心的部分就是下面這一塊:
關於講解,我就直接寫在代碼裏面,用中文來對其進行詳細的一個介紹。相對應的代碼如下:
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): attn = torch.matmul(q / self.temperature, k.transpose(2, 3)) # query和每個key進行相似度計算得到權重 if mask is not None: attn = attn.masked_fill(mask == 0, -1e9) attn = self.dropout(F.softmax(attn, dim=-1)) # 使用一個softmax函數對這些權重進行歸一化 output = torch.matmul(attn, v) # 權重和相應的鍵值value進行加權求和得到最後的attention return output, attn
相對應的公式和圖,看下面。
除了點積之外,還可以用cosine的相似性、mlp網絡等來計算score
class MultiHeadAttention(nn.Module): ''' Multi-Head Attention module ''' def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super().__init__() self.n_head = n_head # 注意力頭的數目,說白了就是你想吧hidden_size 分成幾部分來分別計算,一般取8/12 self.d_k = d_k # 每個注意力頭的大小 self.d_v = d_v # 每個注意力頭的大小 # d_model == n_head*d_k self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False) # 這裏的d_model=q的hidden_size 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) # d_model=hidden_size def forward(self, q, k, v, mask=None): # 一般q!=(k==v),如果是self_atten,就是q==k==v 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) # q:(batch, seq_len, hidden_size) residual = q # 保留原始的q,後面做完attention之後要把原始的q進行相加,具體看上圖最左邊的黑色箭頭 q = self.layer_norm(q) # q:(batch, seq_len, hidden_size) # 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) # (batch, seq_len, n_head, d_k) 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, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) # (batch, n_head, seq_len, d_k) if mask is not None: mask = mask.unsqueeze(1) # For head axis broadcasting. q, attn = self.attention(q, k, v, mask=mask) # 要計算atten係數和更新之後的q # 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) # (batch, seq_len, hidden_size) q = self.dropout(self.fc(q)) q += residual # 將原始的q進行相加 return q, attn # attn裏面是所有的係數,其實已經用過了,就沒啥作用了,主要保留的是經過atten之後的q
class PositionwiseFeedForward(nn.Module): ''' A two-feed-forward-layer module ''' def __init__(self, d_in, d_hid, dropout=0.1): super().__init__() self.w_1 = nn.Linear(d_in, d_hid) # position-wise self.w_2 = nn.Linear(d_hid, d_in) # position-wise self.layer_norm = nn.LayerNorm(d_in, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, x): residual = x x = self.layer_norm(x) x = self.w_2(F.relu(self.w_1(x))) x = self.dropout(x) x += residual return x