当前位置:   article > 正文

从attention到Transformer+CV中的self-attention_将自self-attention扩展到transformer体系结构

将自self-attention扩展到transformer体系结构

一.总体结构

由于rnn等循环神经网络有时序依赖,导致无法并行计算,而Transformer主体框架是一个encoder-decoder结构,去掉了RNN序列结构,完全基于attention和全连接。同时为了弥补词与词之间时序信息,将词位置embedding成向量输入模型.

二.每一步拆分

1.padding mask

对于输入序列一般我们都要进行padding补齐,也就是说设定一个统一长度N,在较短的序列后面填充0到长度为N。对于那些补零的数据来说,我们的attention机制不应该把注意力放在这些位置上,所以我们需要进行一些处理。具体的做法是,把这些位置的值加上一个非常大的负数(负无穷),这样经过softmax后,这些位置的权重就会接近0。Transformer的padding mask实际上是一个张量,每个值都是一个Boolean,值为false的地方就是要进行处理的地方。

  1. def padding_mask(seq_k, seq_q):
  2. len_q = seq_q.size(1)
  3. print('=len_q:', len_q)
  4. # `PAD` is 0
  5. pad_mask_ = seq_k.eq(0)#每句话的pad mask
  6. print('==pad_mask_:', pad_mask_)
  7. pad_mask = pad_mask_.unsqueeze(1).expand(-1, len_q, -1) # shape [B, L_q, L_k]#作用于attention的mask
  8. print('==pad_mask', pad_mask)
  9. return pad_mask
  10. def debug_padding_mask():
  11. Bs = 2
  12. inputs_len = np.random.randint(1, 5, Bs).reshape(Bs, 1)
  13. print('==inputs_len:', inputs_len)
  14. vocab_size = 6000 # 词汇数
  15. max_seq_len = int(max(inputs_len))
  16. # vocab_size = int(max(inputs_len))
  17. x = np.zeros((Bs, max_seq_len), dtype=np.int)
  18. for s in range(Bs):
  19. for j in range(inputs_len[s][0]):
  20. x[s][j] = j + 1
  21. x = torch.LongTensor(torch.from_numpy(x))
  22. print('x.shape', x.shape)
  23. mask = padding_mask(seq_k=x, seq_q=x)
  24. print('==mask:', mask.shape)
  25. if __name__ == '__main__':
  26. debug_padding_mask()

2.Position encoding

其也叫做Position embedding,由于Transformer模型没有使用RNN,故Position encoding(PE)的目的就是实现文本序列的顺序(或者说位置)信息而出现的。

代码实现如下:输入batch内的词位置,输出是batch内的每个词的位置embedding向量.

  1. class PositionalEncoding(nn.Module):
  2. def __init__(self, d_model, max_seq_len):
  3. """初始化
  4. Args:
  5. d_model: 一个标量。模型的维度,论文默认是512
  6. max_seq_len: 一个标量。文本序列的最大长度
  7. """
  8. super(PositionalEncoding, self).__init__()
  9. # 根据论文给的公式,构造出PE矩阵
  10. position_encoding = np.array([
  11. [pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)]
  12. for pos in range(max_seq_len)]).astype(np.float32)
  13. # 偶数列使用sin,奇数列使用cos
  14. position_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])
  15. position_encoding[:, 1::2] = np.cos(position_encoding[:, 1::2])
  16. # 在PE矩阵的第一行,加上一行全是0的向量,代表这`PAD`的positional encoding
  17. # 在word embedding中也经常会加上`UNK`,代表位置单词的word embedding,两者十分类似
  18. # 那么为什么需要这个额外的PAD的编码呢?很简单,因为文本序列的长度不一,我们需要对齐,
  19. # 短的序列我们使用0在结尾补全,我们也需要这些补全位置的编码,也就是`PAD`对应的位置编码
  20. position_encoding = torch.from_numpy(position_encoding) # [max_seq_len, model_dim]
  21. # print('==position_encoding.shape:', position_encoding.shape)
  22. pad_row = torch.zeros([1, d_model])
  23. position_encoding = torch.cat((pad_row, position_encoding)) # [max_seq_len+1, model_dim]
  24. # print('==position_encoding.shape:', position_encoding.shape)
  25. # 嵌入操作,+1是因为增加了`PAD`这个补全位置的编码,
  26. # Word embedding中如果词典增加`UNK`,我们也需要+1。看吧,两者十分相似
  27. self.position_encoding = nn.Embedding(max_seq_len + 1, d_model)
  28. self.position_encoding.weight = nn.Parameter(position_encoding,
  29. requires_grad=False)
  30. def forward(self, input_len):
  31. """神经网络的前向传播。
  32. Args:
  33. input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。
  34. Returns:
  35. 返回这一批序列的位置编码,进行了对齐。
  36. """
  37. # 找出这一批序列的最大长度
  38. max_len = torch.max(input_len)
  39. tensor = torch.cuda.LongTensor if input_len.is_cuda else torch.LongTensor
  40. # 对每一个序列的位置进行对齐,在原序列位置的后面补上0
  41. # 这里range从1开始也是因为要避开PAD(0)的位置
  42. input_pos = tensor(
  43. [list(range(1, len + 1)) + [0] * (max_len - len) for len in input_len])
  44. # print('==input_pos:', input_pos)#pad补齐
  45. # print('==input_pos.shape:', input_pos.shape)#[bs, max_len]
  46. return self.position_encoding(input_pos)
  47. def debug_posion():
  48. """d_model:模型的维度"""
  49. bs = 16
  50. x_sclar = np.random.randint(1, 30, bs).reshape(bs, 1)
  51. model = PositionalEncoding(d_model=512, max_seq_len=int(max(x_sclar)))
  52. x = torch.from_numpy(x_sclar)#[bs, 1]
  53. print('===x:', x)
  54. print('====x.shape', x.shape)
  55. out = model(x)
  56. print('==out.shape:', out.shape)#[bs, max_seq_len, model_dim]
  57. if __name__ == '__main__':
  58. debug_posion()

3.Scaled dot-product attention实现

Q,K,V:可看成一个batch内词的三个embedding向量和矩阵相乘得到的,而这个矩阵就是需要学习的,通过Q,K获取attention score作用于V上获取加权的V.这样一句话的不同词就获取了不同关注度.注意,Q,K,V这 3 个向量一般比原来的词向量的长度更小。假设这 3 个向量的长度是64 ,而原始的词向量或者最终输出的向量的长度是 512(Q,K,V这 3 个向量的长度,和最终输出的向量长度,是有倍数关系的)

上图中,有两个词向量:Thinking 的词向量 x1 和 Machines 的词向量 x2。以 x1 为例,X1 乘以 WQ 得到 q1,q1 就是 X1 对应的 Query 向量。同理,X1 乘以 WK 得到 k1,k1 是 X1 对应的 Key 向量;X1 乘以 WV 得到 v1,v1 是 X1 对应的 Value 向量。

对应代码实现: 

  1. class ScaledDotProductAttention(nn.Module):
  2. """Scaled dot-product attention mechanism."""
  3. def __init__(self, attention_dropout=0.5):
  4. super(ScaledDotProductAttention, self).__init__()
  5. self.dropout = nn.Dropout(attention_dropout)
  6. self.softmax = nn.Softmax(dim=2)
  7. def forward(self, q, k, v, scale=None, attn_mask=None):
  8. """前向传播.
  9. Args:
  10. q: Queries张量,形状为[B, L_q, D_q]
  11. k: Keys张量,形状为[B, L_k, D_k]
  12. v: Values张量,形状为[B, L_v, D_v],一般来说就是k
  13. scale: 缩放因子,一个浮点标量
  14. attn_mask: Masking张量,形状为[B, L_q, L_k]
  15. Returns:
  16. 上下文张量和attetention张量
  17. """
  18. attention = torch.bmm(q, k.transpose(1, 2)) # [B, sequence, sequence]
  19. print('===attention.shape', attention)
  20. if scale:
  21. attention = attention * scale
  22. if attn_mask is not None:
  23. # 给需要mask的地方设置一个负无穷
  24. attention = attention.masked_fill_(attn_mask, -np.inf)
  25. print('===attention.shape', attention)
  26. attention = self.softmax(attention) # [B, sequence, sequence]
  27. # print('===attention.shape', attention.shape)
  28. attention = self.dropout(attention) # [B, sequence, sequence]
  29. # print('===attention.shape', attention.shape)
  30. context = torch.bmm(attention, v) # [B, sequence, dim]
  31. return context, attention
  32. def debug_scale_attention():
  33. model = ScaledDotProductAttention()
  34. # B, L_q, D_q = 32, 100, 128
  35. B, L_q, D_q = 2, 4, 10
  36. pading_mask = torch.tensor([[[False, False, False, False],
  37. [False, False, False, False],
  38. [False, False, False, False],
  39. [False, False, False, False]],
  40. [[False, False, True, True],
  41. [False, False, True, True],
  42. [False, False, True, True],
  43. [False, False, True, True]]])
  44. q, k, v = torch.rand(B, L_q, D_q), torch.rand(B, L_q, D_q), torch.rand(B, L_q, D_q)
  45. print('==q.shape:', q.shape)
  46. print('====k.shape', k.shape)
  47. print('==v.shape:', v.shape)
  48. out = model(q, k, v, attn_mask=pading_mask)
  49. if __name__ == '__main__':
  50. debug_scale_attention()

注意q和k,v维度可以不一样

  1. import torch.nn as nn
  2. d_model = 256
  3. nhead = 8
  4. multihead_attn1 = nn.MultiheadAttention(d_model, nhead, dropout=0.1)
  5. src1 = torch.rand((256, 1, 256))
  6. src2 = torch.rand((1024, 1, 256))
  7. src2_key_padding_mask = torch.zeros((1, 1024))
  8. src12 = multihead_attn1(query=src1,
  9. key=src2,
  10. value=src2, attn_mask=None,
  11. key_padding_mask=src2_key_padding_mask)[0]
  12. print('=src12.shape:', src12.shape)
  13. key_padding_mask = torch.zeros((1, 1024))
  14. num_heads = 8
  15. q = torch.rand((256, 1, 256))
  16. tgt_len, bsz, embed_dim = q.size()
  17. head_dim = embed_dim // num_heads
  18. q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
  19. print('==q.shape:', q.shape)
  20. k = torch.rand((1024, 1, 256))
  21. v = torch.rand((1024, 1, 256))
  22. k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
  23. src_len = k.size(1)
  24. v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
  25. print('==k.shape:', k.shape)
  26. print('==v.shape:', v.shape)
  27. attn_output_weights = torch.bmm(q, k.transpose(1, 2))
  28. print('==attn_output_weights.shape:', attn_output_weights.shape)
  29. if key_padding_mask is not None:
  30. attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
  31. attn_output_weights = attn_output_weights.masked_fill(
  32. key_padding_mask.unsqueeze(1).unsqueeze(2),
  33. float('-inf'),
  34. )
  35. attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, src_len)
  36. attn_output_weights = F.softmax(
  37. attn_output_weights, dim=-1)
  38. print('==attn_output_weights.shape:', attn_output_weights.shape)
  39. attn_output = torch.bmm(attn_output_weights, v)
  40. print('==attn_output.shape:', attn_output.shape)
  41. attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
  42. print('==attn_output.shape:', attn_output.shape)

 

4.Multi-Head Attention

                      

其中H就是Multi-Head可看出首先对Q,K,V进行一次线性变换,然后进行切分,对每一个切分的部分进行attention(Scaled dot-product attention),然后最后将结果进行合并.有一种类似通道加权的感觉.

对应代码实现: 

  1. class MultiHeadAttention(nn.Module):
  2. def __init__(self, model_dim=512, num_heads=8, dropout=0.0):
  3. """model_dim:词向量维度
  4. num_heads:头个数
  5. """
  6. super(MultiHeadAttention, self).__init__()
  7. self.dim_per_head = model_dim // num_heads#split个数也就是每个head要处理维度
  8. self.num_heads = num_heads
  9. self.linear_k = nn.Linear(model_dim, self.dim_per_head * num_heads)
  10. self.linear_v = nn.Linear(model_dim, self.dim_per_head * num_heads)
  11. self.linear_q = nn.Linear(model_dim, self.dim_per_head * num_heads)
  12. self.dot_product_attention = ScaledDotProductAttention(dropout)
  13. self.linear_final = nn.Linear(model_dim, model_dim)
  14. self.dropout = nn.Dropout(dropout)
  15. self.layer_norm = nn.LayerNorm(model_dim)
  16. def forward(self, key, value, query, attn_mask=None):
  17. residual = query# [B, sequence, model_dim]
  18. dim_per_head = self.dim_per_head
  19. num_heads = self.num_heads
  20. batch_size = key.size(0)
  21. # linear projection
  22. key = self.linear_k(key)# [B, sequence, model_dim]
  23. value = self.linear_v(value)# [B, sequence, model_dim]
  24. query = self.linear_q(query)# [B, sequence, model_dim]
  25. # print('===key.shape:', key.shape)
  26. # print('===value.shape:', value.shape)
  27. # print('==query.shape:', query.shape)
  28. # split by heads
  29. key = key.view(batch_size * num_heads, -1, dim_per_head)# [B* num_heads, sequence, model_dim//*num_heads]
  30. value = value.view(batch_size * num_heads, -1, dim_per_head)# [B* num_heads, sequence, model_dim//*num_heads]
  31. query = query.view(batch_size * num_heads, -1, dim_per_head)# [B* num_heads, sequence, model_dim//*num_heads]
  32. # print('===key.shape:', key.shape)
  33. # print('===value.shape:', value.shape)
  34. # print('==query.shape:', query.shape)
  35. if attn_mask:
  36. attn_mask = attn_mask.repeat(num_heads, 1, 1)
  37. # scaled dot product attention
  38. scale = (key.size(-1) // num_heads) ** -0.5
  39. context, attention = self.dot_product_attention(
  40. query, key, value, scale, attn_mask)
  41. # print('===context.shape', context.shape)# [B* num_heads, sequence, model_dim//*num_heads]
  42. # print('===attention.shape', attention.shape)# [B* num_heads, sequence, sequence]
  43. # concat heads
  44. context = context.view(batch_size, -1, dim_per_head * num_heads)# [B, sequence, model_dim]
  45. # print('===context.shape', context.shape)
  46. # final linear projection
  47. output = self.linear_final(context)# [B, sequence, model_dim]
  48. # print('===context.shape', context.shape)
  49. # dropout
  50. output = self.dropout(output)
  51. # add residual and norm layer
  52. output = self.layer_norm(residual + output)# [B, sequence, model_dim]
  53. # print('==output.shape:', output.shape)
  54. return output, attention
  55. def debug_mutil_head_attention():
  56. model = MultiHeadAttention()
  57. B, L_q, D_q = 32, 100, 512
  58. q, k, v = torch.rand(B, L_q, D_q), torch.rand(B, L_q, D_q), torch.rand(B, L_q, D_q)
  59. # print('==q.shape:', q.shape)# [B, sequence, model_dim]
  60. # print('====k.shape', k.shape)# [B, sequence, model_dim]
  61. # print('==v.shape:', v.shape)# [B, sequence, model_dim]
  62. out, _ = model(q, k, v)# [B, sequence, model_dim]
  63. print('==out.shape:', out.shape)
  64. if __name__ == '__main__':
  65. debug_mutil_head_attention()

5.Positional-wise feed forward network(前馈神经网络层)

如上图中画框就是其所在,

代码:

  1. #Position-wise Feed Forward Networks
  2. class PositionalWiseFeedForward(nn.Module):
  3. def __init__(self, model_dim=512, ffn_dim=2048, dropout=0.0):
  4. """model_dim:词向量的维度
  5. ffn_dim:卷积输出的维度
  6. """
  7. super(PositionalWiseFeedForward, self).__init__()
  8. self.w1 = nn.Conv1d(model_dim, ffn_dim, 1)
  9. self.w2 = nn.Conv1d(ffn_dim, model_dim, 1)
  10. self.dropout = nn.Dropout(dropout)
  11. self.layer_norm = nn.LayerNorm(model_dim)
  12. def forward(self, x):#[B, sequence, model_dim]
  13. output = x.transpose(1, 2)#[B, model_dim, sequence]
  14. # print('===output.shape:', output.shape)
  15. output = self.w2(F.relu(self.w1(output)))#[B, model_dim, sequence]
  16. output = self.dropout(output.transpose(1, 2))#[B, sequence, model_dim]
  17. # add residual and norm layer
  18. output = self.layer_norm(x + output)
  19. return output
  20. def debug_PositionalWiseFeedForward():
  21. B, L_q, D_q = 32, 100, 512
  22. x = torch.rand(B, L_q, D_q)
  23. model = PositionalWiseFeedForward()
  24. out = model(x)
  25. print('==out.shape:', out.shape)
  26. if __name__ == '__main__':
  27. debug_PositionalWiseFeedForward()

6.encoder实现

其共有6层4,5的结构,可看出q k v 均来自同一文本.

  1. def sequence_mask(seq):
  2. batch_size, seq_len = seq.size()
  3. mask = torch.triu(torch.ones((seq_len, seq_len), dtype=torch.uint8),
  4. diagonal=1)
  5. mask = mask.unsqueeze(0).expand(batch_size, -1, -1) # [B, L, L]
  6. return mask
  7. def padding_mask(seq_k, seq_q):
  8. len_q = seq_q.size(1)
  9. # `PAD` is 0
  10. pad_mask = seq_k.eq(0)
  11. pad_mask = pad_mask.unsqueeze(1).expand(-1, len_q, -1) # shape [B, L_q, L_k]
  12. return pad_mask
  13. class EncoderLayer(nn.Module):
  14. """一个encode的layer实现"""
  15. def __init__(self, model_dim=512, num_heads=8, ffn_dim=2018, dropout=0.0):
  16. super(EncoderLayer, self).__init__()
  17. self.attention = MultiHeadAttention(model_dim, num_heads, dropout)
  18. self.feed_forward = PositionalWiseFeedForward(model_dim, ffn_dim, dropout)
  19. def forward(self, inputs, attn_mask=None):
  20. # self attention
  21. # [B, sequence, model_dim] [B* num_heads, sequence, sequence]
  22. context, attention = self.attention(inputs, inputs, inputs, attn_mask)
  23. # feed forward network
  24. output = self.feed_forward(context) # [B, sequence, model_dim]
  25. return output, attention
  26. class Encoder(nn.Module):
  27. """编码器实现 总共6层"""
  28. def __init__(self,
  29. vocab_size,
  30. max_seq_len,
  31. num_layers=6,
  32. model_dim=512,
  33. num_heads=8,
  34. ffn_dim=2048,
  35. dropout=0.0):
  36. super(Encoder, self).__init__()
  37. self.encoder_layers = nn.ModuleList(
  38. [EncoderLayer(model_dim, num_heads, ffn_dim, dropout) for _ in range(num_layers)])
  39. self.seq_embedding = nn.Embedding(vocab_size + 1, model_dim, padding_idx=0)
  40. self.pos_embedding = PositionalEncoding(model_dim, max_seq_len)
  41. # [bs, max_seq_len] [bs, 1]
  42. def forward(self, inputs, inputs_len):
  43. output = self.seq_embedding(inputs) # [bs, max_seq_len, model_dim]
  44. print('========output.shape', output.shape)
  45. # 加入位置信息embedding
  46. output += self.pos_embedding(inputs_len) # [bs, max_seq_len, model_dim]
  47. print('========output.shape', output.shape)
  48. self_attention_mask = padding_mask(inputs, inputs)
  49. attentions = []
  50. for encoder in self.encoder_layers:
  51. output, attention = encoder(output, attn_mask=None)
  52. # output, attention = encoder(output, self_attention_mask)
  53. attentions.append(attention)
  54. return output, attentions
  55. def debug_encoder():
  56. Bs = 16
  57. inputs_len = np.random.randint(1, 30, Bs).reshape(Bs, 1)
  58. # print('==inputs_len:', inputs_len) # 模拟获取每个词的长度
  59. vocab_size = 6000 # 词汇数
  60. max_seq_len = int(max(inputs_len))
  61. # vocab_size = int(max(inputs_len))
  62. x = np.zeros((Bs, max_seq_len), dtype=np.int)
  63. for s in range(Bs):
  64. for j in range(inputs_len[s][0]):
  65. x[s][j] = j+1
  66. x = torch.LongTensor(torch.from_numpy(x))
  67. inputs_len = torch.from_numpy(inputs_len)#[Bs, 1]
  68. model = Encoder(vocab_size=vocab_size, max_seq_len=max_seq_len)
  69. # x = torch.LongTensor([list(range(1, max_seq_len + 1)) for _ in range(Bs)])#模拟每个单词
  70. print('==x.shape:', x.shape)
  71. print(x)
  72. model(x, inputs_len=inputs_len)
  73. if __name__ == '__main__':
  74. debug_encoder()

7.Sequence Mask

样本:“我/爱/机器/学习”和 "i/ love /machine/ learning"

训练:
7.1. 把“我/爱/机器/学习”embedding后输入到encoder里去,最后一层的encoder最终输出的outputs [10, 512](假设我们采用的embedding长度为512,而且batch size = 1),此outputs 乘以新的参数矩阵,可以作为decoder里每一层用到的K和V;

7.2. 将<bos>作为decoder的初始输入,将decoder的最大概率输出词 A1和‘i’做cross entropy计算error。

7.3. 将<bos>,"i" 作为decoder的输入,将decoder的最大概率输出词 A2 和‘love’做cross entropy计算error。

7.4. 将<bos>,"i","love" 作为decoder的输入,将decoder的最大概率输出词A3和'machine' 做cross entropy计算error。

7.5. 将<bos>,"i","love ","machine" 作为decoder的输入,将decoder最大概率输出词A4和‘learning’做cross entropy计算error。

7.6. 将<bos>,"i","love ","machine","learning" 作为decoder的输入,将decoder最大概率输出词A5和终止符</s>做cross entropy计算error。

可看出上述训练过程是挨个单词串行进行的,故引入sequence mask,用于并行训练.

作用生成

8.decoder实现

也是循环6层,可以看出decoder的soft-attention,q来自于decoder,k和v来自于encoder。它体现的是encoder对decoder的加权贡献。

  1. class DecoderLayer(nn.Module):
  2. """解码器的layer实现"""
  3. def __init__(self, model_dim, num_heads=8, ffn_dim=2048, dropout=0.0):
  4. super(DecoderLayer, self).__init__()
  5. self.attention = MultiHeadAttention(model_dim, num_heads, dropout)
  6. self.feed_forward = PositionalWiseFeedForward(model_dim, ffn_dim, dropout)
  7. # [B, sequence, model_dim] [B, sequence, model_dim]
  8. def forward(self,
  9. dec_inputs,
  10. enc_outputs,
  11. self_attn_mask=None,
  12. context_attn_mask=None):
  13. # self attention, all inputs are decoder inputs
  14. # [B, sequence, model_dim] [B* num_heads, sequence, sequence]
  15. dec_output, self_attention = self.attention(
  16. key=dec_inputs, value=dec_inputs, query=dec_inputs, attn_mask=self_attn_mask)
  17. # context attention
  18. # query is decoder's outputs, key and value are encoder's inputs
  19. # [B, sequence, model_dim] [B* num_heads, sequence, sequence]
  20. dec_output, context_attention = self.attention(
  21. key=enc_outputs, value=enc_outputs, query=dec_output, attn_mask=context_attn_mask)
  22. # decoder's output, or context
  23. dec_output = self.feed_forward(dec_output) # [B, sequence, model_dim]
  24. return dec_output, self_attention, context_attention
  25. class Decoder(nn.Module):
  26. """解码器"""
  27. def __init__(self,
  28. vocab_size,
  29. max_seq_len,
  30. num_layers=6,
  31. model_dim=512,
  32. num_heads=8,
  33. ffn_dim=2048,
  34. dropout=0.0):
  35. super(Decoder, self).__init__()
  36. self.num_layers = num_layers
  37. self.decoder_layers = nn.ModuleList(
  38. [DecoderLayer(model_dim, num_heads, ffn_dim, dropout) for _ in
  39. range(num_layers)])
  40. self.seq_embedding = nn.Embedding(vocab_size + 1, model_dim, padding_idx=0)
  41. self.pos_embedding = PositionalEncoding(model_dim, max_seq_len)
  42. def forward(self, inputs, inputs_len, enc_output, context_attn_mask=None):
  43. output = self.seq_embedding(inputs)
  44. output += self.pos_embedding(inputs_len)
  45. print('==output.shape:', output.shape)
  46. self_attention_padding_mask = padding_mask(inputs, inputs)
  47. seq_mask = sequence_mask(inputs)
  48. self_attn_mask = torch.gt((self_attention_padding_mask + seq_mask), 0)
  49. self_attentions = []
  50. context_attentions = []
  51. for decoder in self.decoder_layers:
  52. # [B, sequence, model_dim] [B* num_heads, sequence, sequence] [B* num_heads, sequence, sequence]
  53. output, self_attn, context_attn = decoder(
  54. output, enc_output, self_attn_mask=None, context_attn_mask=None)
  55. self_attentions.append(self_attn)
  56. context_attentions.append(context_attn)
  57. return output, self_attentions, context_attentions
  58. def debug_decoder():
  59. Bs = 2
  60. model_dim = 512
  61. vocab_size = 6000 #词汇数
  62. inputs_len = np.random.randint(1, 5, Bs).reshape(Bs, 1)#batch里每句话的单词个数
  63. inputs_len = torch.from_numpy(inputs_len) # [Bs, 1]
  64. max_seq_len = int(max(inputs_len))
  65. x = np.zeros((Bs, max_seq_len), dtype=np.int)
  66. for s in range(Bs):
  67. for j in range(inputs_len[s][0]):
  68. x[s][j] = j + 1
  69. x = torch.LongTensor(torch.from_numpy(x))#模拟每个单词
  70. # x = torch.LongTensor([list(range(1, max_seq_len + 1)) for _ in range(Bs)])
  71. print('==x:', x)
  72. print('==x.shape:', x.shape)
  73. model = Decoder(vocab_size=vocab_size, max_seq_len=max_seq_len, model_dim=model_dim)
  74. enc_output = torch.rand(Bs, max_seq_len, model_dim) #[B, sequence, model_dim]
  75. print('==enc_output.shape:', enc_output.shape)
  76. out, self_attentions, context_attentions = model(inputs=x, inputs_len=inputs_len, enc_output=enc_output)
  77. print('==out.shape:', out.shape)#[B, sequence, model_dim]
  78. print('==len(self_attentions):', len(self_attentions), self_attentions[0].shape)
  79. print('==len(context_attentions):', len(context_attentions), context_attentions[0].shape)
  80. if __name__ == '__main__':
  81. debug_decoder()

9.transformer

将encoder和decoder组合起来即可.

  1. class Transformer(nn.Module):
  2. def __init__(self,
  3. src_vocab_size,
  4. src_max_len,
  5. tgt_vocab_size,
  6. tgt_max_len,
  7. num_layers=6,
  8. model_dim=512,
  9. num_heads=8,
  10. ffn_dim=2048,
  11. dropout=0.2):
  12. super(Transformer, self).__init__()
  13. self.encoder = Encoder(src_vocab_size, src_max_len, num_layers, model_dim,
  14. num_heads, ffn_dim, dropout)
  15. self.decoder = Decoder(tgt_vocab_size, tgt_max_len, num_layers, model_dim,
  16. num_heads, ffn_dim, dropout)
  17. self.linear = nn.Linear(model_dim, tgt_vocab_size, bias=False)
  18. self.softmax = nn.Softmax(dim=2)
  19. def forward(self, src_seq, src_len, tgt_seq, tgt_len):
  20. context_attn_mask = padding_mask(tgt_seq, src_seq)
  21. print('==context_attn_mask.shape', context_attn_mask.shape)
  22. output, enc_self_attn = self.encoder(src_seq, src_len)
  23. output, dec_self_attn, ctx_attn = self.decoder(
  24. tgt_seq, tgt_len, output, context_attn_mask)
  25. output = self.linear(output)
  26. output = self.softmax(output)
  27. return output, enc_self_attn, dec_self_attn, ctx_attn
  28. def debug_transoform():
  29. Bs = 4
  30. #需要翻译的
  31. encode_inputs_len = np.random.randint(1, 10, Bs).reshape(Bs, 1)
  32. src_vocab_size = 6000 # 词汇数
  33. encode_max_seq_len = int(max(encode_inputs_len))
  34. encode_x = np.zeros((Bs, encode_max_seq_len), dtype=np.int)
  35. for s in range(Bs):
  36. for j in range(encode_inputs_len[s][0]):
  37. encode_x[s][j] = j + 1
  38. encode_x = torch.LongTensor(torch.from_numpy(encode_x))
  39. #翻译的结果
  40. decode_inputs_len = np.random.randint(1, 10, Bs).reshape(Bs, 1)
  41. target_vocab_size = 5000 # 词汇数
  42. decode_max_seq_len = int(max(decode_inputs_len))
  43. decode_x = np.zeros((Bs, decode_max_seq_len), dtype=np.int)
  44. for s in range(Bs):
  45. for j in range(decode_inputs_len[s][0]):
  46. decode_x[s][j] = j + 1
  47. decode_x = torch.LongTensor(torch.from_numpy(decode_x))
  48. encode_inputs_len = torch.from_numpy(encode_inputs_len) # [Bs, 1]
  49. decode_inputs_len = torch.from_numpy(decode_inputs_len) # [Bs, 1]
  50. model = Transformer(src_vocab_size=src_vocab_size, src_max_len=encode_max_seq_len, tgt_vocab_size=target_vocab_size, tgt_max_len=decode_max_seq_len)
  51. # x = torch.LongTensor([list(range(1, max_seq_len + 1)) for _ in range(Bs)])#模拟每个单词
  52. print('==encode_x.shape:', encode_x.shape)
  53. print('==decode_x.shape:', decode_x.shape)
  54. model(encode_x, encode_inputs_len, decode_x, decode_inputs_len)
  55. if __name__ == '__main__':
  56. debug_transoform()

10.总结

(1):相比lstm而言,其能够实现并行,而lstm由于依赖上一时刻只能串行输出;
(2):利用self-attention将每个词之间距离缩短为1,大大缓解了长距离依赖问题,所以网络相比lstm能够堆叠得更深;
(3):Transformer可以同时融合前后位置的信息,而双向LSTM只是简单的将两个方向的结果相加,严格来说仍然是单向的;
(4):完全基于attention的Transformer,可以表达字与字之间的相关关系,可解释性更强;
(5):Transformer位置信息只能依靠position encoding,故当语句较短时效果不一定比lstm好;
(6):attention计算量为O(n^2), n为文本长度,计算量较大;
(7):相比CNN能够捕获全局的信息,而不是局部信息,所以CNN缺乏对数据的整体把握。

三.CV中的self-attention

介绍完了nlp的self-attention,现在介绍CV中的,如下图所示。

1.feature map通过1*1卷积获得,q,k,v三个向量,q与k转置相乘得到attention矩阵,进行softmax归一化到0到1,在作用于V,得到每个像素的加权.

2.softmax

3,加权求和

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class Self_Attn(nn.Module):
  5. """ Self attention Layer"""
  6. def __init__(self, in_dim):
  7. super(Self_Attn, self).__init__()
  8. self.chanel_in = in_dim
  9. self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)
  10. self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)
  11. self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)
  12. self.gamma = nn.Parameter(torch.zeros(1))
  13. self.softmax = nn.Softmax(dim=-1)
  14. def forward(self, x):
  15. """
  16. inputs :
  17. x : input feature maps( B * C * W * H)
  18. returns :
  19. out : self attention value + input feature
  20. attention: B * N * N (N is Width*Height)
  21. """
  22. m_batchsize, C, width, height = x.size()
  23. proj_query = self.query_conv(x).view(m_batchsize, -1, width * height).permute(0, 2, 1) # B*N*C
  24. proj_key = self.key_conv(x).view(m_batchsize, -1, width * height) # B*C*N
  25. energy = torch.bmm(proj_query, proj_key) # batch的matmul B*N*N
  26. attention = self.softmax(energy) # B * (N) * (N)
  27. proj_value = self.value_conv(x).view(m_batchsize, -1, width * height) # B * C * N
  28. out = torch.bmm(proj_value, attention.permute(0, 2, 1)) # B*C*N
  29. out = out.view(m_batchsize, C, width, height) # B*C*H*W
  30. out = self.gamma * out + x
  31. return out, attention
  32. def debug_attention():
  33. attention_module = Self_Attn(in_dim=128)
  34. #B,C,H,W
  35. x = torch.rand((2, 128, 100, 100))
  36. attention_module(x)
  37. if __name__ == '__main__':
  38. debug_attention()

参考:

举个例子讲下transformer的输入输出细节及其他 - 知乎

The Illustrated Transformer – Jay Alammar – Visualizing machine learning one concept at a time.

machine-learning-notes/transformer_pytorch.ipynb at master · luozhouyang/machine-learning-notes · GitHub

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

闽ICP备14008679号