multihead_att.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import os
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. class MultiHeadedAttentionSANM(nn.Module):
  6. def __init__(self, model):
  7. super().__init__()
  8. self.d_k = model.d_k
  9. self.h = model.h
  10. self.linear_out = model.linear_out
  11. self.linear_q_k_v = model.linear_q_k_v
  12. self.fsmn_block = model.fsmn_block
  13. self.pad_fn = model.pad_fn
  14. self.attn = None
  15. self.all_head_size = self.h * self.d_k
  16. def forward(self, x, mask):
  17. mask_3d_btd, mask_4d_bhlt = mask
  18. q_h, k_h, v_h, v = self.forward_qkv(x)
  19. fsmn_memory = self.forward_fsmn(v, mask_3d_btd)
  20. q_h = q_h * self.d_k**(-0.5)
  21. scores = torch.matmul(q_h, k_h.transpose(-2, -1))
  22. att_outs = self.forward_attention(v_h, scores, mask_4d_bhlt)
  23. return att_outs + fsmn_memory
  24. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  25. new_x_shape = x.size()[:-1] + (self.h, self.d_k)
  26. x = x.view(new_x_shape)
  27. return x.permute(0, 2, 1, 3)
  28. def forward_qkv(self, x):
  29. q_k_v = self.linear_q_k_v(x)
  30. q, k, v = torch.split(q_k_v, int(self.h * self.d_k), dim=-1)
  31. q_h = self.transpose_for_scores(q)
  32. k_h = self.transpose_for_scores(k)
  33. v_h = self.transpose_for_scores(v)
  34. return q_h, k_h, v_h, v
  35. def forward_fsmn(self, inputs, mask):
  36. # b, t, d = inputs.size()
  37. # mask = torch.reshape(mask, (b, -1, 1))
  38. inputs = inputs * mask
  39. x = inputs.transpose(1, 2)
  40. x = self.pad_fn(x)
  41. x = self.fsmn_block(x)
  42. x = x.transpose(1, 2)
  43. x = x + inputs
  44. x = x * mask
  45. return x
  46. def forward_attention(self, value, scores, mask):
  47. scores = scores + mask
  48. self.attn = torch.softmax(scores, dim=-1)
  49. context_layer = torch.matmul(self.attn, value) # (batch, head, time1, d_k)
  50. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  51. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  52. context_layer = context_layer.view(new_context_layer_shape)
  53. return self.linear_out(context_layer) # (batch, time1, d_model)
  54. class MultiHeadedAttentionSANMDecoder(nn.Module):
  55. def __init__(self, model):
  56. super().__init__()
  57. self.fsmn_block = model.fsmn_block
  58. self.pad_fn = model.pad_fn
  59. self.kernel_size = model.kernel_size
  60. self.attn = None
  61. def forward(self, inputs, mask, cache=None):
  62. # b, t, d = inputs.size()
  63. # mask = torch.reshape(mask, (b, -1, 1))
  64. inputs = inputs * mask
  65. x = inputs.transpose(1, 2)
  66. if cache is None:
  67. x = self.pad_fn(x)
  68. else:
  69. x = torch.cat((cache[:, :, 1:], x), dim=2)
  70. cache = x
  71. x = self.fsmn_block(x)
  72. x = x.transpose(1, 2)
  73. x = x + inputs
  74. x = x * mask
  75. return x, cache
  76. class MultiHeadedAttentionCrossAtt(nn.Module):
  77. def __init__(self, model):
  78. super().__init__()
  79. self.d_k = model.d_k
  80. self.h = model.h
  81. self.linear_q = model.linear_q
  82. self.linear_k_v = model.linear_k_v
  83. self.linear_out = model.linear_out
  84. self.attn = None
  85. self.all_head_size = self.h * self.d_k
  86. def forward(self, x, memory, memory_mask):
  87. q, k, v = self.forward_qkv(x, memory)
  88. scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
  89. return self.forward_attention(v, scores, memory_mask)
  90. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  91. new_x_shape = x.size()[:-1] + (self.h, self.d_k)
  92. x = x.view(new_x_shape)
  93. return x.permute(0, 2, 1, 3)
  94. def forward_qkv(self, x, memory):
  95. q = self.linear_q(x)
  96. k_v = self.linear_k_v(memory)
  97. k, v = torch.split(k_v, int(self.h * self.d_k), dim=-1)
  98. q = self.transpose_for_scores(q)
  99. k = self.transpose_for_scores(k)
  100. v = self.transpose_for_scores(v)
  101. return q, k, v
  102. def forward_attention(self, value, scores, mask):
  103. scores = scores + mask
  104. self.attn = torch.softmax(scores, dim=-1)
  105. context_layer = torch.matmul(self.attn, value) # (batch, head, time1, d_k)
  106. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  107. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  108. context_layer = context_layer.view(new_context_layer_shape)
  109. return self.linear_out(context_layer) # (batch, time1, d_model)
  110. class OnnxMultiHeadedAttention(nn.Module):
  111. def __init__(self, model):
  112. super().__init__()
  113. self.d_k = model.d_k
  114. self.h = model.h
  115. self.linear_q = model.linear_q
  116. self.linear_k = model.linear_k
  117. self.linear_v = model.linear_v
  118. self.linear_out = model.linear_out
  119. self.attn = None
  120. self.all_head_size = self.h * self.d_k
  121. def forward(self, query, key, value, mask):
  122. q, k, v = self.forward_qkv(query, key, value)
  123. scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
  124. return self.forward_attention(v, scores, mask)
  125. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  126. new_x_shape = x.size()[:-1] + (self.h, self.d_k)
  127. x = x.view(new_x_shape)
  128. return x.permute(0, 2, 1, 3)
  129. def forward_qkv(self, query, key, value):
  130. q = self.linear_q(query)
  131. k = self.linear_k(key)
  132. v = self.linear_v(value)
  133. q = self.transpose_for_scores(q)
  134. k = self.transpose_for_scores(k)
  135. v = self.transpose_for_scores(v)
  136. return q, k, v
  137. def forward_attention(self, value, scores, mask):
  138. scores = scores + mask
  139. self.attn = torch.softmax(scores, dim=-1)
  140. context_layer = torch.matmul(self.attn, value) # (batch, head, time1, d_k)
  141. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  142. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  143. context_layer = context_layer.view(new_context_layer_shape)
  144. return self.linear_out(context_layer) # (batch, time1, d_model)
  145. class OnnxRelPosMultiHeadedAttention(OnnxMultiHeadedAttention):
  146. def __init__(self, model):
  147. super().__init__(model)
  148. self.linear_pos = model.linear_pos
  149. self.pos_bias_u = model.pos_bias_u
  150. self.pos_bias_v = model.pos_bias_v
  151. def forward(self, query, key, value, pos_emb, mask):
  152. q, k, v = self.forward_qkv(query, key, value)
  153. q = q.transpose(1, 2) # (batch, time1, head, d_k)
  154. p = self.transpose_for_scores(self.linear_pos(pos_emb)) # (batch, head, time1, d_k)
  155. # (batch, head, time1, d_k)
  156. q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)
  157. # (batch, head, time1, d_k)
  158. q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)
  159. # compute attention score
  160. # first compute matrix a and matrix c
  161. # as described in https://arxiv.org/abs/1901.02860 Section 3.3
  162. # (batch, head, time1, time2)
  163. matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
  164. # compute matrix b and matrix d
  165. # (batch, head, time1, time1)
  166. matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
  167. matrix_bd = self.rel_shift(matrix_bd)
  168. scores = (matrix_ac + matrix_bd) / math.sqrt(
  169. self.d_k
  170. ) # (batch, head, time1, time2)
  171. return self.forward_attention(v, scores, mask)
  172. def rel_shift(self, x):
  173. zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)
  174. x_padded = torch.cat([zero_pad, x], dim=-1)
  175. x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))
  176. x = x_padded[:, :, 1:].view_as(x)[
  177. :, :, :, : x.size(-1) // 2 + 1
  178. ] # only keep the positions from 0 to time2
  179. return x
  180. def forward_attention(self, value, scores, mask):
  181. scores = scores + mask
  182. self.attn = torch.softmax(scores, dim=-1)
  183. context_layer = torch.matmul(self.attn, value) # (batch, head, time1, d_k)
  184. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  185. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  186. context_layer = context_layer.view(new_context_layer_shape)
  187. return self.linear_out(context_layer) # (batch, time1, d_model)