encoder.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import math
  2. import torch
  3. import torch.nn.functional as F
  4. from torch import nn
  5. class MultiHeadSelfAttention(nn.Module):
  6. def __init__(self, n_units, h=8, dropout_rate=0.1):
  7. super(MultiHeadSelfAttention, self).__init__()
  8. self.linearQ = nn.Linear(n_units, n_units)
  9. self.linearK = nn.Linear(n_units, n_units)
  10. self.linearV = nn.Linear(n_units, n_units)
  11. self.linearO = nn.Linear(n_units, n_units)
  12. self.d_k = n_units // h
  13. self.h = h
  14. self.dropout = nn.Dropout(dropout_rate)
  15. def __call__(self, x, batch_size, x_mask):
  16. q = self.linearQ(x).view(batch_size, -1, self.h, self.d_k)
  17. k = self.linearK(x).view(batch_size, -1, self.h, self.d_k)
  18. v = self.linearV(x).view(batch_size, -1, self.h, self.d_k)
  19. scores = torch.matmul(
  20. q.permute(0, 2, 1, 3), k.permute(0, 2, 3, 1)) / math.sqrt(self.d_k)
  21. if x_mask is not None:
  22. x_mask = x_mask.unsqueeze(1)
  23. scores = scores.masked_fill(x_mask == 0, -1e9)
  24. self.att = F.softmax(scores, dim=3)
  25. p_att = self.dropout(self.att)
  26. x = torch.matmul(p_att, v.permute(0, 2, 1, 3))
  27. x = x.permute(0, 2, 1, 3).contiguous().view(-1, self.h * self.d_k)
  28. return self.linearO(x)
  29. class PositionwiseFeedForward(nn.Module):
  30. def __init__(self, n_units, d_units, dropout_rate):
  31. super(PositionwiseFeedForward, self).__init__()
  32. self.linear1 = nn.Linear(n_units, d_units)
  33. self.linear2 = nn.Linear(d_units, n_units)
  34. self.dropout = nn.Dropout(dropout_rate)
  35. def __call__(self, x):
  36. return self.linear2(self.dropout(F.relu(self.linear1(x))))
  37. class PositionalEncoding(torch.nn.Module):
  38. def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
  39. super(PositionalEncoding, self).__init__()
  40. self.d_model = d_model
  41. self.reverse = reverse
  42. self.xscale = math.sqrt(self.d_model)
  43. self.dropout = torch.nn.Dropout(p=dropout_rate)
  44. self.pe = None
  45. self.extend_pe(torch.tensor(0.0).expand(1, max_len))
  46. def extend_pe(self, x):
  47. if self.pe is not None:
  48. if self.pe.size(1) >= x.size(1):
  49. if self.pe.dtype != x.dtype or self.pe.device != x.device:
  50. self.pe = self.pe.to(dtype=x.dtype, device=x.device)
  51. return
  52. pe = torch.zeros(x.size(1), self.d_model)
  53. if self.reverse:
  54. position = torch.arange(
  55. x.size(1) - 1, -1, -1.0, dtype=torch.float32
  56. ).unsqueeze(1)
  57. else:
  58. position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
  59. div_term = torch.exp(
  60. torch.arange(0, self.d_model, 2, dtype=torch.float32)
  61. * -(math.log(10000.0) / self.d_model)
  62. )
  63. pe[:, 0::2] = torch.sin(position * div_term)
  64. pe[:, 1::2] = torch.cos(position * div_term)
  65. pe = pe.unsqueeze(0)
  66. self.pe = pe.to(device=x.device, dtype=x.dtype)
  67. def forward(self, x: torch.Tensor):
  68. self.extend_pe(x)
  69. x = x * self.xscale + self.pe[:, : x.size(1)]
  70. return self.dropout(x)
  71. class EENDOLATransformerEncoder(nn.Module):
  72. def __init__(self,
  73. idim: int,
  74. n_layers: int,
  75. n_units: int,
  76. e_units: int = 2048,
  77. h: int = 8,
  78. dropout_rate: float = 0.1,
  79. use_pos_emb: bool = False):
  80. super(EENDOLATransformerEncoder, self).__init__()
  81. self.lnorm_in = nn.LayerNorm(n_units)
  82. self.n_layers = n_layers
  83. self.dropout = nn.Dropout(dropout_rate)
  84. for i in range(n_layers):
  85. setattr(self, '{}{:d}'.format("lnorm1_", i),
  86. nn.LayerNorm(n_units))
  87. setattr(self, '{}{:d}'.format("self_att_", i),
  88. MultiHeadSelfAttention(n_units, h))
  89. setattr(self, '{}{:d}'.format("lnorm2_", i),
  90. nn.LayerNorm(n_units))
  91. setattr(self, '{}{:d}'.format("ff_", i),
  92. PositionwiseFeedForward(n_units, e_units, dropout_rate))
  93. self.lnorm_out = nn.LayerNorm(n_units)
  94. if use_pos_emb:
  95. self.pos_enc = torch.nn.Sequential(
  96. torch.nn.Linear(idim, n_units),
  97. torch.nn.LayerNorm(n_units),
  98. torch.nn.Dropout(dropout_rate),
  99. torch.nn.ReLU(),
  100. PositionalEncoding(n_units, dropout_rate),
  101. )
  102. else:
  103. self.linear_in = nn.Linear(idim, n_units)
  104. self.pos_enc = None
  105. def __call__(self, x, x_mask=None):
  106. BT_size = x.shape[0] * x.shape[1]
  107. if self.pos_enc is not None:
  108. e = self.pos_enc(x)
  109. e = e.view(BT_size, -1)
  110. else:
  111. e = self.linear_in(x.reshape(BT_size, -1))
  112. for i in range(self.n_layers):
  113. e = getattr(self, '{}{:d}'.format("lnorm1_", i))(e)
  114. s = getattr(self, '{}{:d}'.format("self_att_", i))(e, x.shape[0], x_mask)
  115. e = e + self.dropout(s)
  116. e = getattr(self, '{}{:d}'.format("lnorm2_", i))(e)
  117. s = getattr(self, '{}{:d}'.format("ff_", i))(e)
  118. e = e + self.dropout(s)
  119. return self.lnorm_out(e)