当前位置:   article > 正文

注意力机制学习:Multi-Head Attention_height-axis multi-head attention module

height-axis multi-head attention module

多头注意力机制(Mutil-head Attention):多头注意( Multihead Attention )是注意机制模块。

实现:通过一个注意力机制的多次并行运行,将独立的注意力输出串联起来,线性地转化为预期维度。直观看来,多个注意头允许对序列的不同部分进行注意力运算。

\text{MultiHead}\left(\textbf{Q}, \textbf{K}, \textbf{V}\right) = \left[\text{head}_{1},\dots,\text{head}_{h}\right]\textbf{W}_{0}

\text{where} \text{ head}_{i} = \text{Attention} \left(\textbf{Q}\textbf{W}_{i}^{Q}, \textbf{K}\textbf{W}_{i}^{K}, \textbf{V}\textbf{W}_{i}^{V} \right)

 

 其中,\textbf{W}都是可学习的参数矩阵。

注:缩放点积注意力(Scaled dot-product attention)在这个模块中很常用的,同时也可以将其换为其他类型的注意力机制。

 

  1. import numpy as np
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class ScaledDotProductAttention(nn.Module):
  5. ''' Scaled Dot-Product Attention '''
  6. def __init__(self, temperature, attn_dropout=0.1):
  7. super().__init__()
  8. self.temperature = temperature
  9. self.dropout = nn.Dropout(attn_dropout)
  10. def forward(self, q, k, v, mask=None):
  11. attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
  12. if mask is not None:
  13. attn = attn.masked_fill(mask == 0, -1e9)
  14. attn = self.dropout(F.softmax(attn, dim=-1))
  15. output = torch.matmul(attn, v)
  16. return output, attn
  17. class MultiHeadAttention(nn.Module):
  18. ''' Multi-Head Attention module '''
  19. def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
  20. super().__init__()
  21. self.n_head = n_head
  22. self.d_k = d_k
  23. self.d_v = d_v
  24. self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
  25. self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
  26. self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
  27. self.fc = nn.Linear(n_head * d_v, d_model, bias=False)
  28. self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)
  29. self.dropout = nn.Dropout(dropout)
  30. self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
  31. def forward(self, q, k, v, mask=None):
  32. d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
  33. sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
  34. residual = q
  35. # Pass through the pre-attention projection: b x lq x (n*dv)
  36. # Separate different heads: b x lq x n x dv
  37. q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
  38. k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
  39. v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
  40. # Transpose for attention dot product: b x n x lq x dv
  41. q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
  42. if mask is not None:
  43. mask = mask.unsqueeze(1) # For head axis broadcasting.
  44. q, attn = self.attention(q, k, v, mask=mask)
  45. # Transpose to move the head dimension back: b x lq x n x dv
  46. # Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)
  47. q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
  48. q = self.dropout(self.fc(q))
  49. q += residual
  50. q = self.layer_norm(q)
  51. return q, attn
  52. class PositionwiseFeedForward(nn.Module):
  53. ''' A two-feed-forward-layer module '''
  54. def __init__(self, d_in, d_hid, dropout=0.1):
  55. super().__init__()
  56. self.w_1 = nn.Linear(d_in, d_hid) # position-wise
  57. self.w_2 = nn.Linear(d_hid, d_in) # position-wise
  58. self.layer_norm = nn.LayerNorm(d_in, eps=1e-6)
  59. self.dropout = nn.Dropout(dropout)
  60. def forward(self, x):
  61. residual = x
  62. x = self.w_2(F.relu(self.w_1(x)))
  63. x = self.dropout(x)
  64. x += residual
  65. x = self.layer_norm(x)
  66. return x

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/907030
推荐阅读
相关标签
  

闽ICP备14008679号