You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SubLayers.py 2.8 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. ''' Define the sublayers in encoder/decoder layer '''
  2. import numpy as np
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from transformer.Modules import ScaledDotProductAttention
  6. __author__ = "Yu-Hsiang Huang"
  7. class MultiHeadAttention(nn.Module):
  8. ''' Multi-Head Attention module '''
  9. def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
  10. super().__init__()
  11. self.n_head = n_head
  12. self.d_k = d_k
  13. self.d_v = d_v
  14. self.w_qs = nn.Linear(d_model, n_head * d_k)
  15. self.w_ks = nn.Linear(d_model, n_head * d_k)
  16. self.w_vs = nn.Linear(d_model, n_head * d_v)
  17. nn.init.xavier_normal_(self.w_qs.weight)
  18. nn.init.xavier_normal_(self.w_ks.weight)
  19. nn.init.xavier_normal_(self.w_vs.weight)
  20. self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))
  21. self.layer_norm = nn.LayerNorm(d_model)
  22. self.fc = nn.Linear(n_head * d_v, d_model)
  23. nn.init.xavier_normal_(self.fc.weight)
  24. self.dropout = nn.Dropout(dropout)
  25. def forward(self, q, k, v, mask=None):
  26. d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
  27. sz_b, len_q, _ = q.size()
  28. sz_b, len_k, _ = k.size()
  29. sz_b, len_v, _ = v.size()
  30. residual = q
  31. q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
  32. k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
  33. v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
  34. q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk
  35. k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk
  36. v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv
  37. if mask is not None:
  38. mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..
  39. output, attn = self.attention(q, k, v, mask=mask)
  40. output = output.view(n_head, sz_b, len_q, d_v)
  41. output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)
  42. output = self.dropout(self.fc(output))
  43. output = self.layer_norm(output + residual)
  44. return output, attn
  45. class PositionwiseFeedForward(nn.Module):
  46. ''' A two-feed-forward-layer module '''
  47. def __init__(self, d_in, d_hid, dropout=0.1):
  48. super().__init__()
  49. self.w_1 = nn.Conv1d(d_in, d_hid, 1) # position-wise
  50. self.w_2 = nn.Conv1d(d_hid, d_in, 1) # position-wise
  51. self.layer_norm = nn.LayerNorm(d_in)
  52. self.dropout = nn.Dropout(dropout)
  53. def forward(self, x):
  54. residual = x
  55. output = x.transpose(1, 2)
  56. output = self.w_2(F.relu(self.w_1(output)))
  57. output = output.transpose(1, 2)
  58. output = self.dropout(output)
  59. output = self.layer_norm(output + residual)
  60. return output