目录
Model部分的源码如下:
data部分的源码如下
对于data部分的代码分析
1.Encoder部分的代码分析
(1)在Encoder中首先进入的是Embedding层。
(2)在Encoder中第二次进入的是Positional层。
(3)在Encoder中第三次进入的是get_attn_pad_mask,
(4)最后一步进入的是layer层,也就是Encoderlayer层,最主要的计算都在这里。
多头注意力的部分,
代码来自b站up:数学家是我理想
代码总体分为三个部分,data部分是测试用的数据,为手动输入为了方便理解代码的流程比较简单。model部分是整个模型的代码流程。
Model部分的源码如下:
import math
import torch
import numpy as np
import torch.nn as nn
# Transformer Parameters
from transformer_data import src_vocab_size, target_vocab_size
d_model = 512 # Embedding Size
d_ff = 2048 # FeedForward dimension
d_k = d_v = 64 # dimension of K(=Q), V
n_layers = 6 # number of Encoder of Decoder Layer
n_heads = 8 # number of heads in Multi-Head Attention
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
#pe的维度是(5000,512)
pe = torch.zeros(max_len, d_model)
#position是一个5000行1列的tensor
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
#div_term是一个256长度的一维tensor
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
#最终的pe是一个torch.Size([5000, 1, 512])的维度
self.register_buffer('pe', pe)
def forward(self, x):
'''
x: [seq_len, batch_size, d_model]
'''
x = x + self.pe[:x.size(0), :]
return self.dropout(x)
def get_attn_pad_mask(seq_q, seq_k):
'''
seq_q: [batch_size, seq_len]
seq_k: [batch_size, seq_len]
seq_len could be src_len or it could be tgt_len
seq_len in seq_q and seq_len in seq_k maybe not equal
'''
batch_size, len_q = seq_q.size()
batch_size, len_k = seq_k.size()
# eq(zero) is PAD token
pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # [batch_size, 1, len_k], True is masked
return pad_attn_mask.expand(batch_size, len_q, len_k) # [batch_size, len_q, len_k]
def get_attn_subsequence_mask(seq):
'''
seq: [batch_size, tgt_len]
'''
attn_shape = [seq.size(0), seq.size(1), seq.size(1)]
subsequence_mask = np.triu(np.ones(attn_shape), k=1) # Upper triangular matrix
subsequence_mask = torch.from_numpy(subsequence_mask).byte()
return subsequence_mask # [batch_size, tgt_len, tgt_len]
class ScaledDotProductAttention(nn.Module):
def __init__(self):
super(ScaledDotProductAttention, self).__init__()
def forward(self, Q, K, V, attn_mask):
'''
Q: [batch_size, n_heads, len_q, d_k]
K: [batch_size, n_heads, len_k, d_k]
V: [batch_size, n_heads, len_v(=len_k), d_v]
attn_mask: [batch_size, n_heads, seq_len, seq_len]
'''
scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, len_q, len_k]
scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is True.
attn = nn.Softmax(dim=-1)(scores)
context = torch.matmul(attn, V) # [batch_size, n_heads, len_q, d_v]
# print(attn.shape)
# print(V.shape)
# torch.Size([2, 8, 5, 5])
# torch.Size([2, 8, 5, 64])
return context, attn
class MultiHeadAttention(nn.Module):
def __init__(self):
super(MultiHeadAttention, self).__init__()
self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False)
#d_k * n_heads 64 * 8
self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False)
self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)
self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
#input_Q (2,5,512) attn_mask (2,5,5)
def forward(self, input_Q, input_K, input_V, attn_mask):
# '''
# input_Q: [batch_size, len_q, d_model] (2,5,512)
# input_K: [batch_size, len_k, d_model]
# input_V: [batch_size, len_v(=len_k), d_model]
# attn_mask: [batch_size, seq_len, seq_len]
# '''
#print("input_Q的维度", input_Q.shape)
residual, batch_size = input_Q, input_Q.size(0)
# (B, S, D) -proj-> (B, S, D_new) -split-> (B, S, H, W) -trans-> (B, H, S, W)
# D_new这个新的维度就是原本的维度 × n个头,也就是
Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1,2)
# Q: [batch_size, n_heads, len_q, d_k]
#(2,5,512)-> (2,5,8,64) ->
K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1,2)
# K: [batch_size, n_heads, len_k, d_k]
V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)
# V: [batch_size, n_heads, len_v(=len_k), d_v]
# torch.Size([2, 5, 5]) -》([2, 8, 5, 5]) 也就是复制了几份
attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)
# attn_mask : [batch_size, n_heads, seq_len, seq_len]
# context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k]
context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)
# (2,8,5,64)
# (2,8,5,5)
context = context.transpose(1, 2).reshape(batch_size, -1,n_heads * d_v)
# context: [batch_size, len_q, n_heads * d_v]
#2 8 5 64 -> 2 5 8 64 -> 2 5 512
#self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
#8 * 64 -> 512
output = self.fc(context) # [batch_size, len_q, d_model]
print("attn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shape")
print(attn.shape)
return nn.LayerNorm(d_model).cuda()(output + residual), attn
class PoswiseFeedForwardNet(nn.Module):
def __init__(self):
super(PoswiseFeedForwardNet, self).__init__()
self.fc = nn.Sequential(
nn.Linear(d_model, d_ff, bias=False),
nn.ReLU(),
nn.Linear(d_ff, d_model, bias=False)
)
def forward(self, inputs):
'''
inputs: [batch_size, seq_len, d_model]
'''
residual = inputs
output = self.fc(inputs)
return nn.LayerNorm(d_model).cuda()(output + residual) # [batch_size, seq_len, d_model]
# enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
class EncoderLayer(nn.Module):
def __init__(self):
super(EncoderLayer, self).__init__()
self.enc_self_attn = MultiHeadAttention()
self.pos_ffn = PoswiseFeedForwardNet()
def forward(self, enc_inputs, enc_self_attn_mask):
'''
enc_inputs: [batch_size, src_len, d_model]
enc_self_attn_mask: [batch_size, src_len, src_len]
'''
# enc_outputs: [batch_size, src_len, d_model], attn: [batch_size, n_heads, src_len, src_len]
enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V
enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size, src_len, d_model]
return enc_outputs, attn
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.src_emb = nn.Embedding(src_vocab_size, d_model)
#词向量,src_vocab_size 有多少个词库,d_model是要转换的维度。
self.pos_emb = PositionalEncoding(d_model)
#返回的是一个二维的矩阵
self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
def forward(self, enc_inputs):
'''
enc_inputs: [batch_size, src_len]
'''
enc_outputs = self.src_emb(enc_inputs) # [batch_size, src_len, d_model]
enc_outputs = self.pos_emb(enc_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, src_len, d_model]
enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs) # [batch_size, src_len, src_len]
enc_self_attns = []
for layer in self.layers:
# enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
enc_self_attns.append(enc_self_attn)
return enc_outputs, enc_self_attns
class DecoderLayer(nn.Module):
def __init__(self):
super(DecoderLayer, self).__init__()
self.dec_self_attn = MultiHeadAttention()
self.dec_enc_attn = MultiHeadAttention()
self.pos_ffn = PoswiseFeedForwardNet()
def forward(self, dec_inputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask):
'''
dec_inputs: [batch_size, tgt_len, d_model]
enc_outputs: [batch_size, src_len, d_model]
dec_self_attn_mask: [batch_size, tgt_len, tgt_len]
dec_enc_attn_mask: [batch_size, tgt_len, src_len]
'''
# dec_outputs: [batch_size, tgt_len, d_model], dec_self_attn: [batch_size, n_heads, tgt_len, tgt_len]
dec_outputs, dec_self_attn = self.dec_self_attn(dec_inputs, dec_inputs, dec_inputs, dec_self_attn_mask)
# dec_outputs: [batch_size, tgt_len, d_model], dec_enc_attn: [batch_size, h_heads, tgt_len, src_len]
dec_outputs, dec_enc_attn = self.dec_enc_attn(dec_outputs, enc_outputs, enc_outputs, dec_enc_attn_mask)
dec_outputs = self.pos_ffn(dec_outputs) # [batch_size, tgt_len, d_model]
return dec_outputs, dec_self_attn, dec_enc_attn
class Decoder(nn.Module):
def __init__(self):
super(Decoder, self).__init__()
self.tgt_emb = nn.Embedding(target_vocab_size, d_model)
self.pos_emb = PositionalEncoding(d_model)
self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])
def forward(self, dec_inputs, enc_inputs, enc_outputs):
'''
dec_inputs: [batch_size, tgt_len]
enc_intpus: [batch_size, src_len]
enc_outputs: [batch_size, src_len, d_model]
'''
dec_outputs = self.tgt_emb(dec_inputs) # [batch_size, tgt_len, d_model]
dec_outputs = self.pos_emb(dec_outputs.transpose(0, 1)).transpose(0, 1).cuda() # [batch_size, tgt_len, d_model]
dec_self_attn_pad_mask = get_attn_pad_mask(dec_inputs, dec_inputs).cuda() # [batch_size, tgt_len, tgt_len]
dec_self_attn_subsequence_mask = get_attn_subsequence_mask(dec_inputs).cuda() # [batch_size, tgt_len, tgt_len]
dec_self_attn_mask = torch.gt((dec_self_attn_pad_mask + dec_self_attn_subsequence_mask), 0).cuda() # [batch_size, tgt_len, tgt_len]
dec_enc_attn_mask = get_attn_pad_mask(dec_inputs, enc_inputs) # [batc_size, tgt_len, src_len]
dec_self_attns, dec_enc_attns = [], []
for layer in self.layers:
# dec_outputs: [batch_size, tgt_len, d_model], dec_self_attn: [batch_size, n_heads, tgt_len, tgt_len], dec_enc_attn: [batch_size, h_heads, tgt_len, src_len]
dec_outputs, dec_self_attn, dec_enc_attn = layer(dec_outputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask)
dec_self_attns.append(dec_self_attn)
dec_enc_attns.append(dec_enc_attn)
return dec_outputs, dec_self_attns, dec_enc_attns
class Transformer(nn.Module):
def __init__(self):
super(Transformer, self).__init__()
self.encoder = Encoder().cuda()
self.decoder = Decoder().cuda()
#这里的意思是,在encoder和decoder后都变成了512维的,然后再转换成target_vocab_size的维度的
# tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
# idx2word = {i: w for i, w in enumerate(tgt_vocab)}
# idx2word = {0: 'P', 1: 'i', 2: 'want', 3: 'a', 4: 'beer', 5: 'coke', 6: 'S', 7: 'E', 8: '.'}
# target_vocab_size = len(tgt_vocab)
#为什么要转换成 target_vocab_size这个维度呢,因为你有这么多单词,要判断概率最大的是哪一个。
self.projection = nn.Linear(d_model, target_vocab_size, bias=False).cuda()
def forward(self, enc_inputs, dec_inputs):
'''
enc_inputs: [batch_size, src_len]
dec_inputs: [batch_size, tgt_len]
'''
# tensor to store decoder outputs
# outputs = torch.zeros(batch_size, tgt_len, tgt_vocab_size).to(self.device)
# enc_outputs: [batch_size, src_len, d_model], enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
enc_outputs, enc_self_attns = self.encoder(enc_inputs)
# dec_outpus: [batch_size, tgt_len, d_model], dec_self_attns: [n_layers, batch_size, n_heads, tgt_len, tgt_len], dec_enc_attn: [n_layers, batch_size, tgt_len, src_len]
dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)
dec_logits = self.projection(dec_outputs) # dec_logits: [batch_size, tgt_len, tgt_vocab_size]
return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns
data部分的源码如下
import torch
import torch.utils.data as Data
# S: Symbol that shows starting of decoding input
# E: Symbol that shows starting of decoding output
# P: Symbol that will fill in blank sequence if current batch data size is short than time steps
sentences = [
# enc_input dec_input dec_output
['ich mochte ein bier P', 'S i want a beer .', 'i want a beer . E'],
['ich mochte ein cola P', 'S i want a coke .', 'i want a coke . E']
]
# Padding Should be Zero
src_vocab = {'P': 0, 'ich': 1, 'mochte': 2, 'ein': 3, 'bier': 4, 'cola': 5}
src_vocab_size = len(src_vocab)
tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
idx2word = {i: w for i, w in enumerate(tgt_vocab)}
target_vocab_size = len(tgt_vocab)
src_len = 5 # enc_input max sequence length
tgt_len = 6 # dec_input(=dec_output) max sequence length
def make_data(sentences):
enc_inputs, dec_inputs, dec_outputs = [], [], []
for i in range(len(sentences)):
enc_input = [[src_vocab[n] for n in sentences[i][0].split()]] # [[1, 2, 3, 4, 0], [1, 2, 3, 5, 0]]
dec_input = [[tgt_vocab[n] for n in sentences[i][1].split()]] # [[6, 1, 2, 3, 4, 8], [6, 1, 2, 3, 5, 8]]
dec_output = [[tgt_vocab[n] for n in sentences[i][2].split()]] # [[1, 2, 3, 4, 8, 7], [1, 2, 3, 5, 8, 7]]
enc_inputs.extend(enc_input)
dec_inputs.extend(dec_input)
dec_outputs.extend(dec_output)
return torch.LongTensor(enc_inputs), torch.LongTensor(dec_inputs), torch.LongTensor(dec_outputs)
enc_inputs, dec_inputs, dec_outputs = make_data(sentences)
class MyDataSet(Data.Dataset):
def __init__(self, enc_inputs, dec_inputs, dec_outputs):
super(MyDataSet, self).__init__()
self.enc_inputs = enc_inputs
self.dec_inputs = dec_inputs
self.dec_outputs = dec_outputs
def __len__(self):
return self.enc_inputs.shape[0]
def __getitem__(self, idx):
return self.enc_inputs[idx], self.dec_inputs[idx], self.dec_outputs[idx]
loader = Data.DataLoader(MyDataSet(enc_inputs, dec_inputs, dec_outputs), 2, True)
对于data部分的代码分析
对于loader来说,需要设置的主要有三个参数,第一个参数是数据集,第二个参数是batch_size,也就是一次传入多少个数据。
loader = Data.DataLoader(MyDataSet(enc_inputs, dec_inputs, dec_outputs), 2, True)
对于loader中的数据,可以这样进行遍历。
for enc_inputs, dec_inputs, dec_outputs in loader:
基本的数据的尺度如下,第一个encoder的input是(2,5),第二个decoder的input是(2,6),第三个decoder的output也是(2,6)
tensor([[1, 2, 3, 4, 0],
[1, 2, 3, 5, 0]])
torch.Size([2, 5])
tensor([[6, 1, 2, 3, 4, 8],
[6, 1, 2, 3, 5, 8]])
torch.Size([2, 6])
tensor([[1, 2, 3, 4, 8, 7],
[1, 2, 3, 5, 8, 7]])
torch.Size([2, 6])
对于模型本身来说,首先接收的输入是enc_inputs也就是最初始的数据,(2,6)的维度的input。第一个接收这个原始的inputs的是encoder。
class Transformer(nn.Module):
def __init__(self):
super(Transformer, self).__init__()
self.encoder = Encoder().cuda()
self.decoder = Decoder().cuda()
#这里的意思是,在encoder和decoder后都变成了512维的,然后再转换成target_vocab_size的维度的
# tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
# idx2word = {i: w for i, w in enumerate(tgt_vocab)}
# idx2word = {0: 'P', 1: 'i', 2: 'want', 3: 'a', 4: 'beer', 5: 'coke', 6: 'S', 7: 'E', 8: '.'}
# target_vocab_size = len(tgt_vocab)
#为什么要转换成 target_vocab_size这个维度呢,因为你有这么多单词,要判断概率最大的是哪一个。
self.projection = nn.Linear(d_model, target_vocab_size, bias=False).cuda()
def forward(self, enc_inputs, dec_inputs):
'''
enc_inputs: [batch_size, src_len]
dec_inputs: [batch_size, tgt_len]
'''
# tensor to store decoder outputs
# outputs = torch.zeros(batch_size, tgt_len, tgt_vocab_size).to(self.device)
# enc_outputs: [batch_size, src_len, d_model], enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
enc_outputs, enc_self_attns = self.encoder(enc_inputs)
# dec_outpus: [batch_size, tgt_len, d_model], dec_self_attns: [n_layers, batch_size, n_heads, tgt_len, tgt_len], dec_enc_attn: [n_layers, batch_size, tgt_len, src_len]
dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)
dec_logits = self.projection(dec_outputs) # dec_logits: [batch_size, tgt_len, tgt_vocab_size]
return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns
1.Encoder部分的代码分析
Encoder的初始化函数包括三个部分,
1.词编码(Embedding)
2.位置编码(PositionalEncoding)
3.若干个Encoder层(EncoderLayer)
其中词编码和位置编码都是唯一的,而可以包含若干个EncoderLayer,层数是可以手动设置。
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.src_emb = nn.Embedding(src_vocab_size, d_model)
#词向量,src_vocab_size 有多少个词库,d_model是要转换的维度。
self.pos_emb = PositionalEncoding(d_model)
#返回的是一个二维的矩阵
self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
def forward(self, enc_inputs):
'''
enc_inputs: [batch_size, src_len]
'''
enc_outputs = self.src_emb(enc_inputs) # [batch_size, src_len, d_model]
enc_outputs = self.pos_emb(enc_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, src_len, d_model]
enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs) # [batch_size, src_len, src_len]
enc_self_attns = []
for layer in self.layers:
# enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
enc_self_attns.append(enc_self_attn)
return enc_outputs, enc_self_attns
(1)在Encoder中首先进入的是Embedding层。
init中的词编码如下:
self.src_emb = nn.Embedding(src_vocab_size, d_model)
forward中的词编码如下:
enc_outputs = self.src_emb(enc_inputs)
1)对于nn.Embedding(),他接收两个参数, 一个参数是num_embeddings: int,也就是所编码的这个语言有多少个词库,因为这里数据是手写的,所以很短,是6. src_vocab = {'P': 0, 'ich': 1, 'mochte': 2, 'ein': 3, 'bier': 4, 'cola': 5} src_vocab_size = len(src_vocab) 另一个参数是embedding_dim: int,也就是想要编码生成的维度,在这里是512. 2)对于enc_outputs = self.src_emb(enc_inputs) # [batch_size, src_len, d_model]。输入的是enc_inputs也就是原始的最开始输入的数据,他的维度是(2,5).经过输出之后的维度是(2,5,512)也就是说经过第一层词编码后,所得到的enc_outputs是(2,5,512)的维度。
(2)在Encoder中第二次进入的是Positional层。
在init中的函数如下
self.pos_emb = PositionalEncoding(d_model)
在forward中的函数如下
enc_outputs = self.pos_emb(enc_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, src_len, d_model]
进入positionalembedding层的是经过词编码的outputs也就是(2,5,512)的维度的tensor。
进入positional_embedding前的输入需要进行维度互换,在positional_embedding里面这个输入的维度是(5,2,512)而经过之后的还是(5,2,512)只不过是对于输入的x添加了位置信息。而出来之后的输入又经过了一遍transpose,所以最终的输出的维度还是(2,5,512)。位置编码的代码如下:
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
#pe的维度是(5000,512)
pe = torch.zeros(max_len, d_model)
#position是一个5000行1列的tensor
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
#div_term是一个256长度的一维tensor
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
#最终的pe是一个torch.Size([5000, 1, 512])的维度
self.register_buffer('pe', pe)
def forward(self, x):
'''
x: [seq_len, batch_size, d_model]
'''
x = x + self.pe[:x.size(0), :]
return self.dropout(x)
(3)在Encoder中第三次进入的是get_attn_pad_mask,
在这里seq_q和seq_k都是刚才的输入,原始输入,他的维度是(2,5)
def get_attn_pad_mask(seq_q, seq_k):
'''
seq_q: [batch_size, seq_len]
seq_k: [batch_size, seq_len]
seq_len could be src_len or it could be tgt_len
seq_len in seq_q and seq_len in seq_k maybe not equal
'''
batch_size, len_q = seq_q.size()
batch_size, len_k = seq_k.size()
# eq(zero) is PAD token
pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # [batch_size, 1, len_k], True is masked
return pad_attn_mask.expand(batch_size, len_q, len_k) # [batch_size, len_q, len_k]
这个函数的输出如下图所示:
(4)最后一步进入的是layer层,也就是Encoderlayer层,最主要的计算都在这里。
init中的layer如下
self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
forward中的layer如下
enc_self_attns = []
for layer in self.layers:
# enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
enc_self_attns.append(enc_self_attn)
如图所示,刚才红框的部分就是真正的Encoder所做的事情,
我们发现,EncoderLayer的部分很简单,主要包括两项
(1) MultiHeadAttention(多头注意力)
(2)PoswiseFeedForwardNet(前馈神经网络)
其中多头注意力主要是进行点积的计算也就是QKV的计算,而前馈神经网络主要是信息的凝聚和维度的变换。
class EncoderLayer(nn.Module):
def __init__(self):
super(EncoderLayer, self).__init__()
self.enc_self_attn = MultiHeadAttention()
self.pos_ffn = PoswiseFeedForwardNet()
def forward(self, enc_inputs, enc_self_attn_mask):
'''
enc_inputs: [batch_size, src_len, d_model]
enc_self_attn_mask: [batch_size, src_len, src_len]
'''
# enc_outputs: [batch_size, src_len, d_model], attn: [batch_size, n_heads, src_len, src_len]
enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V
enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size, src_len, d_model]
return enc_outputs, attn
layer(enc_outputs, enc_self_attn_mask),注意这里的输入enc_outputs的维度是(2,5,512),而enc_self_attn_mask的维度是(2,5,5).layer的enc_outputs对应的是EncoderLayers里面的enc_inputs,也就是说对于forward中的enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask), 他传入的三个参数enc_inputs都是上一层的enc_outputs,就是(2,5,512)的维度。enc_self_attn_mask也就是上一层的,其维度为(2,5,5)
多头注意力的部分,
class MultiHeadAttention(nn.Module):
def __init__(self):
super(MultiHeadAttention, self).__init__()
self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False)
#d_k * n_heads 64 * 8
self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False)
self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)
self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
#input_Q (2,5,512) attn_mask (2,5,5)
def forward(self, input_Q, input_K, input_V, attn_mask):
# '''
# input_Q: [batch_size, len_q, d_model] (2,5,512)
# input_K: [batch_size, len_k, d_model]
# input_V: [batch_size, len_v(=len_k), d_model]
# attn_mask: [batch_size, seq_len, seq_len]
# '''
#print("input_Q的维度", input_Q.shape)
residual, batch_size = input_Q, input_Q.size(0)
# (B, S, D) -proj-> (B, S, D_new) -split-> (B, S, H, W) -trans-> (B, H, S, W)
# D_new这个新的维度就是原本的维度 × n个头,也就是
Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1,2)
# Q: [batch_size, n_heads, len_q, d_k]
K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1,2)
# K: [batch_size, n_heads, len_k, d_k]
V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)
# V: [batch_size, n_heads, len_v(=len_k), d_v]
attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)
# attn_mask : [batch_size, n_heads, seq_len, seq_len]
# context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k]
context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)
context = context.transpose(1, 2).reshape(batch_size, -1,n_heads * d_v)
# context: [batch_size, len_q, n_heads * d_v]
output = self.fc(context) # [batch_size, len_q, d_model]
return nn.LayerNorm(d_model).cuda()(output + residual), attn
所谓的W_Q,K,V矩阵就是Linear层,如init中所示:这里的d_k 和 n_heads都是之前设置好的参数,d_k是64,而n_heads是8。
self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False) self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False) self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)
在forwar中,第一步就是获取残差residual 以及batch_size
residual, batch_size = input_Q, input_Q.size(0)
第二步就是获取乘出来的Q,
Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1,2), Q的维度是(2,5,8,64)经过transpose之后(2,8,5,64). W_Q(input_Q)这是第一步,第一步的input_Q的维度是(2,5,512),经过W_Q之后的维度还是 (2,5,512),虽然维度是没有变化,但是所要学习的W_Q也就是这一个Linear层的参数。 同理K和V也是如此: K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1,2) V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2) 总结一下维度的信息,Q,K,V都是(2,8,5,64)
第三步是将之前乘出来的attention_mask进行维度拓展,其实就是复制了n_heads的份数。
attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)进行操作之前,attn_mask的维度是(2,5,5),在进行操作后的维度就是(2,8,5,5),也就是 attn_mask : [batch_size, n_heads, seq_len, seq_len]。 总结一下维度的信息,attn_mask的维度是(2,8,5,5)
第四步是进行点击运算来得到context和attn,所需要的输入是之前利用Linear层和input_q所乘出来的Q,K,V,以及attn_mask。
context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask) # Q,K,V都是(2,8,5,64)。attn_mask的维度是(2,8,5,5)#
具体的ScaledDotProductAttention函数如下所示:
class ScaledDotProductAttention(nn.Module):
def __init__(self):
super(ScaledDotProductAttention, self).__init__()
def forward(self, Q, K, V, attn_mask):
'''
Q: [batch_size, n_heads, len_q, d_k]
K: [batch_size, n_heads, len_k, d_k]
V: [batch_size, n_heads, len_v(=len_k), d_v]
attn_mask: [batch_size, n_heads, seq_len, seq_len]
'''
scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, len_q, len_k]
scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is True.
attn = nn.Softmax(dim=-1)(scores)
context = torch.matmul(attn, V) # [batch_size, n_heads, len_q, d_v]
return context, attn
第一步,scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k),因为Q和K的维度都是(2,8,5,64)将K的维度变换后是(2,8,64,5)所以乘出来的维度是(2,8,5,5)。总结,在这里scores的维度是(2,8,5,5) 第二步,scores.masked_fill_(attn_mask, -1e9),将attn_mask的为true的部分变成负数,这样经过softmax的时候,这个部分就会变成接近于0的数,所以不会产生影响。 第三步,attn = nn.Softmax(dim=-1)(scores),会将其中的每行进行softmax也就是每一行相加是等于1的。如下图所示
第四步,context = torch.matmul(attn, V),return context, attn attn的维度是(2,8,5,5)而V的维度是(2,8,5,64)所以context的维度是(2,8,5,64). 总结一下维度,在第四步输入的attn是(2,8,5,5)而V是(2,8,5,64)所以他俩相乘的维度是(2,8,5,64),最终返回的context的维度就是(2,8,5,64).
第五步,将context的维度从(2,8,5,64)->(2,5,8,64)->(2,5,512)
context = context.transpose(1, 2).reshape(batch_size, -1,n_heads * d_v)
第六步,经过全连接层,然后return,这个全连接层的维度是不变的
output = self.fc(context) return nn.LayerNorm(d_model).cuda()(output + residual), attn 在这里,最终返回的结果的维度是(2,5,512)attn的维度是(2,8,5,5)
class PoswiseFeedForwardNet(nn.Module):
def __init__(self):
super(PoswiseFeedForwardNet, self).__init__()
self.fc = nn.Sequential(
nn.Linear(d_model, d_ff, bias=False),
nn.ReLU(),
nn.Linear(d_ff, d_model, bias=False)
)
def forward(self, inputs):
'''
inputs: [batch_size, seq_len, d_model]
'''
residual = inputs
output = self.fc(inputs)
return nn.LayerNorm(d_model).cuda()(output + residual) # [batch_size, seq_len, d_model]