encoder_layer_mfcca.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2020 Johns Hopkins University (Shinji Watanabe)
  4. # Northwestern Polytechnical University (Pengcheng Guo)
  5. # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  6. """Encoder self-attention layer definition."""
  7. import torch
  8. from torch import nn
  9. from funasr.modules.layer_norm import LayerNorm
  10. from torch.autograd import Variable
  11. class Encoder_Conformer_Layer(nn.Module):
  12. """Encoder layer module.
  13. Args:
  14. size (int): Input dimension.
  15. self_attn (torch.nn.Module): Self-attention module instance.
  16. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance
  17. can be used as the argument.
  18. feed_forward (torch.nn.Module): Feed-forward module instance.
  19. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance
  20. can be used as the argument.
  21. feed_forward_macaron (torch.nn.Module): Additional feed-forward module instance.
  22. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance
  23. can be used as the argument.
  24. conv_module (torch.nn.Module): Convolution module instance.
  25. `ConvlutionModule` instance can be used as the argument.
  26. dropout_rate (float): Dropout rate.
  27. normalize_before (bool): Whether to use layer_norm before the first block.
  28. concat_after (bool): Whether to concat attention layer's input and output.
  29. if True, additional linear will be applied.
  30. i.e. x -> x + linear(concat(x, att(x)))
  31. if False, no additional linear will be applied. i.e. x -> x + att(x)
  32. """
  33. def __init__(
  34. self,
  35. size,
  36. self_attn,
  37. feed_forward,
  38. feed_forward_macaron,
  39. conv_module,
  40. dropout_rate,
  41. normalize_before=True,
  42. concat_after=False,
  43. cca_pos=0,
  44. ):
  45. """Construct an Encoder_Conformer_Layer object."""
  46. super(Encoder_Conformer_Layer, self).__init__()
  47. self.self_attn = self_attn
  48. self.feed_forward = feed_forward
  49. self.feed_forward_macaron = feed_forward_macaron
  50. self.conv_module = conv_module
  51. self.norm_ff = LayerNorm(size) # for the FNN module
  52. self.norm_mha = LayerNorm(size) # for the MHA module
  53. if feed_forward_macaron is not None:
  54. self.norm_ff_macaron = LayerNorm(size)
  55. self.ff_scale = 0.5
  56. else:
  57. self.ff_scale = 1.0
  58. if self.conv_module is not None:
  59. self.norm_conv = LayerNorm(size) # for the CNN module
  60. self.norm_final = LayerNorm(size) # for the final output of the block
  61. self.dropout = nn.Dropout(dropout_rate)
  62. self.size = size
  63. self.normalize_before = normalize_before
  64. self.concat_after = concat_after
  65. self.cca_pos = cca_pos
  66. if self.concat_after:
  67. self.concat_linear = nn.Linear(size + size, size)
  68. def forward(self, x_input, mask, cache=None):
  69. """Compute encoded features.
  70. Args:
  71. x_input (Union[Tuple, torch.Tensor]): Input tensor w/ or w/o pos emb.
  72. - w/ pos emb: Tuple of tensors [(#batch, time, size), (1, time, size)].
  73. - w/o pos emb: Tensor (#batch, time, size).
  74. mask (torch.Tensor): Mask tensor for the input (#batch, time).
  75. cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size).
  76. Returns:
  77. torch.Tensor: Output tensor (#batch, time, size).
  78. torch.Tensor: Mask tensor (#batch, time).
  79. """
  80. if isinstance(x_input, tuple):
  81. x, pos_emb = x_input[0], x_input[1]
  82. else:
  83. x, pos_emb = x_input, None
  84. # whether to use macaron style
  85. if self.feed_forward_macaron is not None:
  86. residual = x
  87. if self.normalize_before:
  88. x = self.norm_ff_macaron(x)
  89. x = residual + self.ff_scale * self.dropout(self.feed_forward_macaron(x))
  90. if not self.normalize_before:
  91. x = self.norm_ff_macaron(x)
  92. # multi-headed self-attention module
  93. residual = x
  94. if self.normalize_before:
  95. x = self.norm_mha(x)
  96. if cache is None:
  97. x_q = x
  98. else:
  99. assert cache.shape == (x.shape[0], x.shape[1] - 1, self.size)
  100. x_q = x[:, -1:, :]
  101. residual = residual[:, -1:, :]
  102. mask = None if mask is None else mask[:, -1:, :]
  103. if self.cca_pos<2:
  104. if pos_emb is not None:
  105. x_att = self.self_attn(x_q, x, x, pos_emb, mask)
  106. else:
  107. x_att = self.self_attn(x_q, x, x, mask)
  108. else:
  109. x_att = self.self_attn(x_q, x, x, mask)
  110. if self.concat_after:
  111. x_concat = torch.cat((x, x_att), dim=-1)
  112. x = residual + self.concat_linear(x_concat)
  113. else:
  114. x = residual + self.dropout(x_att)
  115. if not self.normalize_before:
  116. x = self.norm_mha(x)
  117. # convolution module
  118. if self.conv_module is not None:
  119. residual = x
  120. if self.normalize_before:
  121. x = self.norm_conv(x)
  122. x = residual + self.dropout(self.conv_module(x))
  123. if not self.normalize_before:
  124. x = self.norm_conv(x)
  125. # feed forward module
  126. residual = x
  127. if self.normalize_before:
  128. x = self.norm_ff(x)
  129. x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
  130. if not self.normalize_before:
  131. x = self.norm_ff(x)
  132. if self.conv_module is not None:
  133. x = self.norm_final(x)
  134. if cache is not None:
  135. x = torch.cat([cache, x], dim=1)
  136. if pos_emb is not None:
  137. return (x, pos_emb), mask
  138. return x, mask
  139. class EncoderLayer(nn.Module):
  140. """Encoder layer module.
  141. Args:
  142. size (int): Input dimension.
  143. self_attn (torch.nn.Module): Self-attention module instance.
  144. `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance
  145. can be used as the argument.
  146. feed_forward (torch.nn.Module): Feed-forward module instance.
  147. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance
  148. can be used as the argument.
  149. feed_forward_macaron (torch.nn.Module): Additional feed-forward module instance.
  150. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance
  151. can be used as the argument.
  152. conv_module (torch.nn.Module): Convolution module instance.
  153. `ConvlutionModule` instance can be used as the argument.
  154. dropout_rate (float): Dropout rate.
  155. normalize_before (bool): Whether to use layer_norm before the first block.
  156. concat_after (bool): Whether to concat attention layer's input and output.
  157. if True, additional linear will be applied.
  158. i.e. x -> x + linear(concat(x, att(x)))
  159. if False, no additional linear will be applied. i.e. x -> x + att(x)
  160. """
  161. def __init__(
  162. self,
  163. size,
  164. self_attn_cros_channel,
  165. self_attn_conformer,
  166. feed_forward_csa,
  167. feed_forward_macaron_csa,
  168. conv_module_csa,
  169. dropout_rate,
  170. normalize_before=True,
  171. concat_after=False,
  172. ):
  173. """Construct an EncoderLayer object."""
  174. super(EncoderLayer, self).__init__()
  175. self.encoder_cros_channel_atten = self_attn_cros_channel
  176. self.encoder_csa = Encoder_Conformer_Layer(
  177. size,
  178. self_attn_conformer,
  179. feed_forward_csa,
  180. feed_forward_macaron_csa,
  181. conv_module_csa,
  182. dropout_rate,
  183. normalize_before,
  184. concat_after,
  185. cca_pos=0)
  186. self.norm_mha = LayerNorm(size) # for the MHA module
  187. self.dropout = nn.Dropout(dropout_rate)
  188. def forward(self, x_input, mask, channel_size, cache=None):
  189. """Compute encoded features.
  190. Args:
  191. x_input (Union[Tuple, torch.Tensor]): Input tensor w/ or w/o pos emb.
  192. - w/ pos emb: Tuple of tensors [(#batch, time, size), (1, time, size)].
  193. - w/o pos emb: Tensor (#batch, time, size).
  194. mask (torch.Tensor): Mask tensor for the input (#batch, time).
  195. cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size).
  196. Returns:
  197. torch.Tensor: Output tensor (#batch, time, size).
  198. torch.Tensor: Mask tensor (#batch, time).
  199. """
  200. if isinstance(x_input, tuple):
  201. x, pos_emb = x_input[0], x_input[1]
  202. else:
  203. x, pos_emb = x_input, None
  204. residual = x
  205. x = self.norm_mha(x)
  206. t_leng = x.size(1)
  207. d_dim = x.size(2)
  208. x_new = x.reshape(-1,channel_size,t_leng,d_dim).transpose(1,2) # x_new B*T * C * D
  209. x_k_v = x_new.new(x_new.size(0),x_new.size(1),5,x_new.size(2),x_new.size(3))
  210. pad_before = Variable(torch.zeros(x_new.size(0),2,x_new.size(2),x_new.size(3))).type(x_new.type())
  211. pad_after = Variable(torch.zeros(x_new.size(0),2,x_new.size(2),x_new.size(3))).type(x_new.type())
  212. x_pad = torch.cat([pad_before,x_new, pad_after], 1)
  213. x_k_v[:,:,0,:,:]=x_pad[:,0:-4,:,:]
  214. x_k_v[:,:,1,:,:]=x_pad[:,1:-3,:,:]
  215. x_k_v[:,:,2,:,:]=x_pad[:,2:-2,:,:]
  216. x_k_v[:,:,3,:,:]=x_pad[:,3:-1,:,:]
  217. x_k_v[:,:,4,:,:]=x_pad[:,4:,:,:]
  218. x_new = x_new.reshape(-1,channel_size,d_dim)
  219. x_k_v = x_k_v.reshape(-1,5*channel_size,d_dim)
  220. x_att = self.encoder_cros_channel_atten(x_new, x_k_v, x_k_v, None)
  221. x_att = x_att.reshape(-1,t_leng,channel_size,d_dim).transpose(1,2).reshape(-1,t_leng,d_dim)
  222. x = residual + self.dropout(x_att)
  223. if pos_emb is not None:
  224. x_input = (x, pos_emb)
  225. else:
  226. x_input = x
  227. x_input, mask = self.encoder_csa(x_input, mask)
  228. return x_input, mask , channel_size