当前位置:   article > 正文

Transformer代码逐步解读(pytorch版本)Encoder部分_class encoderlayer(nn.module): def __init__(self,

class encoderlayer(nn.module): def __init__(self, attention, d_model, d_ff=n

目录

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部分的源码如下:

  1. import math
  2. import torch
  3. import numpy as np
  4. import torch.nn as nn
  5. # Transformer Parameters
  6. from transformer_data import src_vocab_size, target_vocab_size
  7. d_model = 512 # Embedding Size
  8. d_ff = 2048 # FeedForward dimension
  9. d_k = d_v = 64 # dimension of K(=Q), V
  10. n_layers = 6 # number of Encoder of Decoder Layer
  11. n_heads = 8 # number of heads in Multi-Head Attention
  12. class PositionalEncoding(nn.Module):
  13. def __init__(self, d_model, dropout=0.1, max_len=5000):
  14. super(PositionalEncoding, self).__init__()
  15. self.dropout = nn.Dropout(p=dropout)
  16. #pe的维度是(5000,512)
  17. pe = torch.zeros(max_len, d_model)
  18. #position是一个5000行1列的tensor
  19. position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
  20. #div_term是一个256长度的一维tensor
  21. div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
  22. pe[:, 0::2] = torch.sin(position * div_term)
  23. pe[:, 1::2] = torch.cos(position * div_term)
  24. pe = pe.unsqueeze(0).transpose(0, 1)
  25. #最终的pe是一个torch.Size([5000, 1, 512])的维度
  26. self.register_buffer('pe', pe)
  27. def forward(self, x):
  28. '''
  29. x: [seq_len, batch_size, d_model]
  30. '''
  31. x = x + self.pe[:x.size(0), :]
  32. return self.dropout(x)
  33. def get_attn_pad_mask(seq_q, seq_k):
  34. '''
  35. seq_q: [batch_size, seq_len]
  36. seq_k: [batch_size, seq_len]
  37. seq_len could be src_len or it could be tgt_len
  38. seq_len in seq_q and seq_len in seq_k maybe not equal
  39. '''
  40. batch_size, len_q = seq_q.size()
  41. batch_size, len_k = seq_k.size()
  42. # eq(zero) is PAD token
  43. pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # [batch_size, 1, len_k], True is masked
  44. return pad_attn_mask.expand(batch_size, len_q, len_k) # [batch_size, len_q, len_k]
  45. def get_attn_subsequence_mask(seq):
  46. '''
  47. seq: [batch_size, tgt_len]
  48. '''
  49. attn_shape = [seq.size(0), seq.size(1), seq.size(1)]
  50. subsequence_mask = np.triu(np.ones(attn_shape), k=1) # Upper triangular matrix
  51. subsequence_mask = torch.from_numpy(subsequence_mask).byte()
  52. return subsequence_mask # [batch_size, tgt_len, tgt_len]
  53. class ScaledDotProductAttention(nn.Module):
  54. def __init__(self):
  55. super(ScaledDotProductAttention, self).__init__()
  56. def forward(self, Q, K, V, attn_mask):
  57. '''
  58. Q: [batch_size, n_heads, len_q, d_k]
  59. K: [batch_size, n_heads, len_k, d_k]
  60. V: [batch_size, n_heads, len_v(=len_k), d_v]
  61. attn_mask: [batch_size, n_heads, seq_len, seq_len]
  62. '''
  63. scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, len_q, len_k]
  64. scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is True.
  65. attn = nn.Softmax(dim=-1)(scores)
  66. context = torch.matmul(attn, V) # [batch_size, n_heads, len_q, d_v]
  67. # print(attn.shape)
  68. # print(V.shape)
  69. # torch.Size([2, 8, 5, 5])
  70. # torch.Size([2, 8, 5, 64])
  71. return context, attn
  72. class MultiHeadAttention(nn.Module):
  73. def __init__(self):
  74. super(MultiHeadAttention, self).__init__()
  75. self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False)
  76. #d_k * n_heads 64 * 8
  77. self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False)
  78. self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)
  79. self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
  80. #input_Q (2,5,512) attn_mask (2,5,5)
  81. def forward(self, input_Q, input_K, input_V, attn_mask):
  82. # '''
  83. # input_Q: [batch_size, len_q, d_model] (2,5,512)
  84. # input_K: [batch_size, len_k, d_model]
  85. # input_V: [batch_size, len_v(=len_k), d_model]
  86. # attn_mask: [batch_size, seq_len, seq_len]
  87. # '''
  88. #print("input_Q的维度", input_Q.shape)
  89. residual, batch_size = input_Q, input_Q.size(0)
  90. # (B, S, D) -proj-> (B, S, D_new) -split-> (B, S, H, W) -trans-> (B, H, S, W)
  91. # D_new这个新的维度就是原本的维度 × n个头,也就是
  92. Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1,2)
  93. # Q: [batch_size, n_heads, len_q, d_k]
  94. #(2,5,512)-> (2,5,8,64) ->
  95. K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1,2)
  96. # K: [batch_size, n_heads, len_k, d_k]
  97. V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)
  98. # V: [batch_size, n_heads, len_v(=len_k), d_v]
  99. # torch.Size([2, 5, 5]) -》([2, 8, 5, 5]) 也就是复制了几份
  100. attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)
  101. # attn_mask : [batch_size, n_heads, seq_len, seq_len]
  102. # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k]
  103. context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)
  104. # (2,8,5,64)
  105. # (2,8,5,5)
  106. context = context.transpose(1, 2).reshape(batch_size, -1,n_heads * d_v)
  107. # context: [batch_size, len_q, n_heads * d_v]
  108. #2 8 5 64 -> 2 5 8 64 -> 2 5 512
  109. #self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
  110. #8 * 64 -> 512
  111. output = self.fc(context) # [batch_size, len_q, d_model]
  112. print("attn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shapeattn.shape")
  113. print(attn.shape)
  114. return nn.LayerNorm(d_model).cuda()(output + residual), attn
  115. class PoswiseFeedForwardNet(nn.Module):
  116. def __init__(self):
  117. super(PoswiseFeedForwardNet, self).__init__()
  118. self.fc = nn.Sequential(
  119. nn.Linear(d_model, d_ff, bias=False),
  120. nn.ReLU(),
  121. nn.Linear(d_ff, d_model, bias=False)
  122. )
  123. def forward(self, inputs):
  124. '''
  125. inputs: [batch_size, seq_len, d_model]
  126. '''
  127. residual = inputs
  128. output = self.fc(inputs)
  129. return nn.LayerNorm(d_model).cuda()(output + residual) # [batch_size, seq_len, d_model]
  130. # enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
  131. class EncoderLayer(nn.Module):
  132. def __init__(self):
  133. super(EncoderLayer, self).__init__()
  134. self.enc_self_attn = MultiHeadAttention()
  135. self.pos_ffn = PoswiseFeedForwardNet()
  136. def forward(self, enc_inputs, enc_self_attn_mask):
  137. '''
  138. enc_inputs: [batch_size, src_len, d_model]
  139. enc_self_attn_mask: [batch_size, src_len, src_len]
  140. '''
  141. # enc_outputs: [batch_size, src_len, d_model], attn: [batch_size, n_heads, src_len, src_len]
  142. enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V
  143. enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size, src_len, d_model]
  144. return enc_outputs, attn
  145. class Encoder(nn.Module):
  146. def __init__(self):
  147. super(Encoder, self).__init__()
  148. self.src_emb = nn.Embedding(src_vocab_size, d_model)
  149. #词向量,src_vocab_size 有多少个词库,d_model是要转换的维度。
  150. self.pos_emb = PositionalEncoding(d_model)
  151. #返回的是一个二维的矩阵
  152. self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
  153. def forward(self, enc_inputs):
  154. '''
  155. enc_inputs: [batch_size, src_len]
  156. '''
  157. enc_outputs = self.src_emb(enc_inputs) # [batch_size, src_len, d_model]
  158. enc_outputs = self.pos_emb(enc_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, src_len, d_model]
  159. enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs) # [batch_size, src_len, src_len]
  160. enc_self_attns = []
  161. for layer in self.layers:
  162. # enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
  163. enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
  164. enc_self_attns.append(enc_self_attn)
  165. return enc_outputs, enc_self_attns
  166. class DecoderLayer(nn.Module):
  167. def __init__(self):
  168. super(DecoderLayer, self).__init__()
  169. self.dec_self_attn = MultiHeadAttention()
  170. self.dec_enc_attn = MultiHeadAttention()
  171. self.pos_ffn = PoswiseFeedForwardNet()
  172. def forward(self, dec_inputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask):
  173. '''
  174. dec_inputs: [batch_size, tgt_len, d_model]
  175. enc_outputs: [batch_size, src_len, d_model]
  176. dec_self_attn_mask: [batch_size, tgt_len, tgt_len]
  177. dec_enc_attn_mask: [batch_size, tgt_len, src_len]
  178. '''
  179. # dec_outputs: [batch_size, tgt_len, d_model], dec_self_attn: [batch_size, n_heads, tgt_len, tgt_len]
  180. dec_outputs, dec_self_attn = self.dec_self_attn(dec_inputs, dec_inputs, dec_inputs, dec_self_attn_mask)
  181. # dec_outputs: [batch_size, tgt_len, d_model], dec_enc_attn: [batch_size, h_heads, tgt_len, src_len]
  182. dec_outputs, dec_enc_attn = self.dec_enc_attn(dec_outputs, enc_outputs, enc_outputs, dec_enc_attn_mask)
  183. dec_outputs = self.pos_ffn(dec_outputs) # [batch_size, tgt_len, d_model]
  184. return dec_outputs, dec_self_attn, dec_enc_attn
  185. class Decoder(nn.Module):
  186. def __init__(self):
  187. super(Decoder, self).__init__()
  188. self.tgt_emb = nn.Embedding(target_vocab_size, d_model)
  189. self.pos_emb = PositionalEncoding(d_model)
  190. self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])
  191. def forward(self, dec_inputs, enc_inputs, enc_outputs):
  192. '''
  193. dec_inputs: [batch_size, tgt_len]
  194. enc_intpus: [batch_size, src_len]
  195. enc_outputs: [batch_size, src_len, d_model]
  196. '''
  197. dec_outputs = self.tgt_emb(dec_inputs) # [batch_size, tgt_len, d_model]
  198. dec_outputs = self.pos_emb(dec_outputs.transpose(0, 1)).transpose(0, 1).cuda() # [batch_size, tgt_len, d_model]
  199. dec_self_attn_pad_mask = get_attn_pad_mask(dec_inputs, dec_inputs).cuda() # [batch_size, tgt_len, tgt_len]
  200. dec_self_attn_subsequence_mask = get_attn_subsequence_mask(dec_inputs).cuda() # [batch_size, tgt_len, tgt_len]
  201. dec_self_attn_mask = torch.gt((dec_self_attn_pad_mask + dec_self_attn_subsequence_mask), 0).cuda() # [batch_size, tgt_len, tgt_len]
  202. dec_enc_attn_mask = get_attn_pad_mask(dec_inputs, enc_inputs) # [batc_size, tgt_len, src_len]
  203. dec_self_attns, dec_enc_attns = [], []
  204. for layer in self.layers:
  205. # 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]
  206. dec_outputs, dec_self_attn, dec_enc_attn = layer(dec_outputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask)
  207. dec_self_attns.append(dec_self_attn)
  208. dec_enc_attns.append(dec_enc_attn)
  209. return dec_outputs, dec_self_attns, dec_enc_attns
  210. class Transformer(nn.Module):
  211. def __init__(self):
  212. super(Transformer, self).__init__()
  213. self.encoder = Encoder().cuda()
  214. self.decoder = Decoder().cuda()
  215. #这里的意思是,在encoder和decoder后都变成了512维的,然后再转换成target_vocab_size的维度的
  216. # tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
  217. # idx2word = {i: w for i, w in enumerate(tgt_vocab)}
  218. # idx2word = {0: 'P', 1: 'i', 2: 'want', 3: 'a', 4: 'beer', 5: 'coke', 6: 'S', 7: 'E', 8: '.'}
  219. # target_vocab_size = len(tgt_vocab)
  220. #为什么要转换成 target_vocab_size这个维度呢,因为你有这么多单词,要判断概率最大的是哪一个。
  221. self.projection = nn.Linear(d_model, target_vocab_size, bias=False).cuda()
  222. def forward(self, enc_inputs, dec_inputs):
  223. '''
  224. enc_inputs: [batch_size, src_len]
  225. dec_inputs: [batch_size, tgt_len]
  226. '''
  227. # tensor to store decoder outputs
  228. # outputs = torch.zeros(batch_size, tgt_len, tgt_vocab_size).to(self.device)
  229. # enc_outputs: [batch_size, src_len, d_model], enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
  230. enc_outputs, enc_self_attns = self.encoder(enc_inputs)
  231. # 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]
  232. dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)
  233. dec_logits = self.projection(dec_outputs) # dec_logits: [batch_size, tgt_len, tgt_vocab_size]
  234. return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns

data部分的源码如下 

  1. import torch
  2. import torch.utils.data as Data
  3. # S: Symbol that shows starting of decoding input
  4. # E: Symbol that shows starting of decoding output
  5. # P: Symbol that will fill in blank sequence if current batch data size is short than time steps
  6. sentences = [
  7. # enc_input dec_input dec_output
  8. ['ich mochte ein bier P', 'S i want a beer .', 'i want a beer . E'],
  9. ['ich mochte ein cola P', 'S i want a coke .', 'i want a coke . E']
  10. ]
  11. # Padding Should be Zero
  12. src_vocab = {'P': 0, 'ich': 1, 'mochte': 2, 'ein': 3, 'bier': 4, 'cola': 5}
  13. src_vocab_size = len(src_vocab)
  14. tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
  15. idx2word = {i: w for i, w in enumerate(tgt_vocab)}
  16. target_vocab_size = len(tgt_vocab)
  17. src_len = 5 # enc_input max sequence length
  18. tgt_len = 6 # dec_input(=dec_output) max sequence length
  19. def make_data(sentences):
  20. enc_inputs, dec_inputs, dec_outputs = [], [], []
  21. for i in range(len(sentences)):
  22. enc_input = [[src_vocab[n] for n in sentences[i][0].split()]] # [[1, 2, 3, 4, 0], [1, 2, 3, 5, 0]]
  23. dec_input = [[tgt_vocab[n] for n in sentences[i][1].split()]] # [[6, 1, 2, 3, 4, 8], [6, 1, 2, 3, 5, 8]]
  24. dec_output = [[tgt_vocab[n] for n in sentences[i][2].split()]] # [[1, 2, 3, 4, 8, 7], [1, 2, 3, 5, 8, 7]]
  25. enc_inputs.extend(enc_input)
  26. dec_inputs.extend(dec_input)
  27. dec_outputs.extend(dec_output)
  28. return torch.LongTensor(enc_inputs), torch.LongTensor(dec_inputs), torch.LongTensor(dec_outputs)
  29. enc_inputs, dec_inputs, dec_outputs = make_data(sentences)
  30. class MyDataSet(Data.Dataset):
  31. def __init__(self, enc_inputs, dec_inputs, dec_outputs):
  32. super(MyDataSet, self).__init__()
  33. self.enc_inputs = enc_inputs
  34. self.dec_inputs = dec_inputs
  35. self.dec_outputs = dec_outputs
  36. def __len__(self):
  37. return self.enc_inputs.shape[0]
  38. def __getitem__(self, idx):
  39. return self.enc_inputs[idx], self.dec_inputs[idx], self.dec_outputs[idx]
  40. 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)

  1. tensor([[1, 2, 3, 4, 0],
  2. [1, 2, 3, 5, 0]])
  3. torch.Size([2, 5])
  4. tensor([[6, 1, 2, 3, 4, 8],
  5. [6, 1, 2, 3, 5, 8]])
  6. torch.Size([2, 6])
  7. tensor([[1, 2, 3, 4, 8, 7],
  8. [1, 2, 3, 5, 8, 7]])
  9. torch.Size([2, 6])

 对于模型本身来说,首先接收的输入是enc_inputs也就是最初始的数据,(2,6)的维度的input。第一个接收这个原始的inputs的是encoder。

  1. class Transformer(nn.Module):
  2. def __init__(self):
  3. super(Transformer, self).__init__()
  4. self.encoder = Encoder().cuda()
  5. self.decoder = Decoder().cuda()
  6. #这里的意思是,在encoder和decoder后都变成了512维的,然后再转换成target_vocab_size的维度的
  7. # tgt_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'coke': 5, 'S': 6, 'E': 7, '.': 8}
  8. # idx2word = {i: w for i, w in enumerate(tgt_vocab)}
  9. # idx2word = {0: 'P', 1: 'i', 2: 'want', 3: 'a', 4: 'beer', 5: 'coke', 6: 'S', 7: 'E', 8: '.'}
  10. # target_vocab_size = len(tgt_vocab)
  11. #为什么要转换成 target_vocab_size这个维度呢,因为你有这么多单词,要判断概率最大的是哪一个。
  12. self.projection = nn.Linear(d_model, target_vocab_size, bias=False).cuda()
  13. def forward(self, enc_inputs, dec_inputs):
  14. '''
  15. enc_inputs: [batch_size, src_len]
  16. dec_inputs: [batch_size, tgt_len]
  17. '''
  18. # tensor to store decoder outputs
  19. # outputs = torch.zeros(batch_size, tgt_len, tgt_vocab_size).to(self.device)
  20. # enc_outputs: [batch_size, src_len, d_model], enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
  21. enc_outputs, enc_self_attns = self.encoder(enc_inputs)
  22. # 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]
  23. dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)
  24. dec_logits = self.projection(dec_outputs) # dec_logits: [batch_size, tgt_len, tgt_vocab_size]
  25. 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,层数是可以手动设置。

  1. class Encoder(nn.Module):
  2. def __init__(self):
  3. super(Encoder, self).__init__()
  4. self.src_emb = nn.Embedding(src_vocab_size, d_model)
  5. #词向量,src_vocab_size 有多少个词库,d_model是要转换的维度。
  6. self.pos_emb = PositionalEncoding(d_model)
  7. #返回的是一个二维的矩阵
  8. self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
  9. def forward(self, enc_inputs):
  10. '''
  11. enc_inputs: [batch_size, src_len]
  12. '''
  13. enc_outputs = self.src_emb(enc_inputs) # [batch_size, src_len, d_model]
  14. enc_outputs = self.pos_emb(enc_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, src_len, d_model]
  15. enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs) # [batch_size, src_len, src_len]
  16. enc_self_attns = []
  17. for layer in self.layers:
  18. # enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
  19. enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
  20. enc_self_attns.append(enc_self_attn)
  21. return enc_outputs, enc_self_attns

 (1)在Encoder中首先进入的是Embedding层

  1. init中的词编码如下:
  2. self.src_emb = nn.Embedding(src_vocab_size, d_model)
  3. forward中的词编码如下:
  4. 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层。

  1. 在init中的函数如下
  2. self.pos_emb = PositionalEncoding(d_model)
  3. 在forward中的函数如下
  4. 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)。位置编码的代码如下:

  1. class PositionalEncoding(nn.Module):
  2. def __init__(self, d_model, dropout=0.1, max_len=5000):
  3. super(PositionalEncoding, self).__init__()
  4. self.dropout = nn.Dropout(p=dropout)
  5. #pe的维度是(5000,512)
  6. pe = torch.zeros(max_len, d_model)
  7. #position是一个5000行1列的tensor
  8. position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
  9. #div_term是一个256长度的一维tensor
  10. div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
  11. pe[:, 0::2] = torch.sin(position * div_term)
  12. pe[:, 1::2] = torch.cos(position * div_term)
  13. pe = pe.unsqueeze(0).transpose(0, 1)
  14. #最终的pe是一个torch.Size([5000, 1, 512])的维度
  15. self.register_buffer('pe', pe)
  16. def forward(self, x):
  17. '''
  18. x: [seq_len, batch_size, d_model]
  19. '''
  20. x = x + self.pe[:x.size(0), :]
  21. return self.dropout(x)

(3)在Encoder中第三次进入的是get_attn_pad_mask,

在这里seq_q和seq_k都是刚才的输入,原始输入,他的维度是(2,5)

  1. def get_attn_pad_mask(seq_q, seq_k):
  2. '''
  3. seq_q: [batch_size, seq_len]
  4. seq_k: [batch_size, seq_len]
  5. seq_len could be src_len or it could be tgt_len
  6. seq_len in seq_q and seq_len in seq_k maybe not equal
  7. '''
  8. batch_size, len_q = seq_q.size()
  9. batch_size, len_k = seq_k.size()
  10. # eq(zero) is PAD token
  11. pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # [batch_size, 1, len_k], True is masked
  12. return pad_attn_mask.expand(batch_size, len_q, len_k) # [batch_size, len_q, len_k]

这个函数的输出如下图所示: 

(4)最后一步进入的是layer层,也就是Encoderlayer层,最主要的计算都在这里。

  1. init中的layer如下
  2. self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
  3. forward中的layer如下
  4. enc_self_attns = []
  5. for layer in self.layers:
  6. # enc_outputs: [batch_size, src_len, d_model], enc_self_attn: [batch_size, n_heads, src_len, src_len]
  7. enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)
  8. enc_self_attns.append(enc_self_attn)

如图所示,刚才红框的部分就是真正的Encoder所做的事情,

我们发现,EncoderLayer的部分很简单,主要包括两项

(1) MultiHeadAttention(多头注意力

(2)PoswiseFeedForwardNet(前馈神经网络)

其中多头注意力主要是进行点积的计算也就是QKV的计算,而前馈神经网络主要是信息的凝聚和维度的变换。

  1. class EncoderLayer(nn.Module):
  2. def __init__(self):
  3. super(EncoderLayer, self).__init__()
  4. self.enc_self_attn = MultiHeadAttention()
  5. self.pos_ffn = PoswiseFeedForwardNet()
  6. def forward(self, enc_inputs, enc_self_attn_mask):
  7. '''
  8. enc_inputs: [batch_size, src_len, d_model]
  9. enc_self_attn_mask: [batch_size, src_len, src_len]
  10. '''
  11. # enc_outputs: [batch_size, src_len, d_model], attn: [batch_size, n_heads, src_len, src_len]
  12. enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V
  13. enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size, src_len, d_model]
  14. 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)

 多头注意力的部分,

  1. class MultiHeadAttention(nn.Module):
  2. def __init__(self):
  3. super(MultiHeadAttention, self).__init__()
  4. self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False)
  5. #d_k * n_heads 64 * 8
  6. self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False)
  7. self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)
  8. self.fc = nn.Linear(n_heads * d_v, d_model, bias=False)
  9. #input_Q (2,5,512) attn_mask (2,5,5)
  10. def forward(self, input_Q, input_K, input_V, attn_mask):
  11. # '''
  12. # input_Q: [batch_size, len_q, d_model] (2,5,512)
  13. # input_K: [batch_size, len_k, d_model]
  14. # input_V: [batch_size, len_v(=len_k), d_model]
  15. # attn_mask: [batch_size, seq_len, seq_len]
  16. # '''
  17. #print("input_Q的维度", input_Q.shape)
  18. residual, batch_size = input_Q, input_Q.size(0)
  19. # (B, S, D) -proj-> (B, S, D_new) -split-> (B, S, H, W) -trans-> (B, H, S, W)
  20. # D_new这个新的维度就是原本的维度 × n个头,也就是
  21. Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1,2)
  22. # Q: [batch_size, n_heads, len_q, d_k]
  23. K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1,2)
  24. # K: [batch_size, n_heads, len_k, d_k]
  25. V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)
  26. # V: [batch_size, n_heads, len_v(=len_k), d_v]
  27. attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)
  28. # attn_mask : [batch_size, n_heads, seq_len, seq_len]
  29. # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k]
  30. context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)
  31. context = context.transpose(1, 2).reshape(batch_size, -1,n_heads * d_v)
  32. # context: [batch_size, len_q, n_heads * d_v]
  33. output = self.fc(context) # [batch_size, len_q, d_model]
  34. 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函数如下所示:

  1. class ScaledDotProductAttention(nn.Module):
  2. def __init__(self):
  3. super(ScaledDotProductAttention, self).__init__()
  4. def forward(self, Q, K, V, attn_mask):
  5. '''
  6. Q: [batch_size, n_heads, len_q, d_k]
  7. K: [batch_size, n_heads, len_k, d_k]
  8. V: [batch_size, n_heads, len_v(=len_k), d_v]
  9. attn_mask: [batch_size, n_heads, seq_len, seq_len]
  10. '''
  11. scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, len_q, len_k]
  12. scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is True.
  13. attn = nn.Softmax(dim=-1)(scores)
  14. context = torch.matmul(attn, V) # [batch_size, n_heads, len_q, d_v]
  15. 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)
  1. class PoswiseFeedForwardNet(nn.Module):
  2. def __init__(self):
  3. super(PoswiseFeedForwardNet, self).__init__()
  4. self.fc = nn.Sequential(
  5. nn.Linear(d_model, d_ff, bias=False),
  6. nn.ReLU(),
  7. nn.Linear(d_ff, d_model, bias=False)
  8. )
  9. def forward(self, inputs):
  10. '''
  11. inputs: [batch_size, seq_len, d_model]
  12. '''
  13. residual = inputs
  14. output = self.fc(inputs)
  15. return nn.LayerNorm(d_model).cuda()(output + residual) # [batch_size, seq_len, d_model]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/528903
推荐阅读
相关标签
  

闽ICP备14008679号