upsample_encoder.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu)
  2. # 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn)
  3. # 2024 Alibaba Inc (Xiang Lyu)
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # Modified from ESPnet(https://github.com/espnet/espnet)
  17. """Encoder definition."""
  18. from typing import Tuple
  19. import torch
  20. from torch import nn
  21. from torch.nn import functional as F
  22. from cosyvoice.transformer.convolution import ConvolutionModule
  23. from cosyvoice.transformer.encoder_layer import ConformerEncoderLayer
  24. from cosyvoice.transformer.positionwise_feed_forward import PositionwiseFeedForward
  25. from cosyvoice.utils.class_utils import (
  26. COSYVOICE_EMB_CLASSES,
  27. COSYVOICE_SUBSAMPLE_CLASSES,
  28. COSYVOICE_ATTENTION_CLASSES,
  29. COSYVOICE_ACTIVATION_CLASSES,
  30. )
  31. from cosyvoice.utils.mask import make_pad_mask
  32. from cosyvoice.utils.mask import add_optional_chunk_mask
  33. class Upsample1D(nn.Module):
  34. """A 1D upsampling layer with an optional convolution.
  35. Parameters:
  36. channels (`int`):
  37. number of channels in the inputs and outputs.
  38. use_conv (`bool`, default `False`):
  39. option to use a convolution.
  40. use_conv_transpose (`bool`, default `False`):
  41. option to use a convolution transpose.
  42. out_channels (`int`, optional):
  43. number of output channels. Defaults to `channels`.
  44. """
  45. def __init__(self, channels: int, out_channels: int, stride: int = 2):
  46. super().__init__()
  47. self.channels = channels
  48. self.out_channels = out_channels
  49. self.stride = stride
  50. # In this mode, first repeat interpolate, than conv with stride=1
  51. self.conv = nn.Conv1d(self.channels, self.out_channels, stride * 2 + 1, stride=1, padding=0)
  52. def forward(self, inputs: torch.Tensor, input_lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  53. outputs = F.interpolate(inputs, scale_factor=float(self.stride), mode="nearest")
  54. outputs = F.pad(outputs, (self.stride * 2, 0), value=0.0)
  55. outputs = self.conv(outputs)
  56. return outputs, input_lengths * self.stride
  57. class PreLookaheadLayer(nn.Module):
  58. def __init__(self, in_channels: int, channels: int, pre_lookahead_len: int = 1):
  59. super().__init__()
  60. self.in_channels = in_channels
  61. self.channels = channels
  62. self.pre_lookahead_len = pre_lookahead_len
  63. self.conv1 = nn.Conv1d(
  64. in_channels, channels,
  65. kernel_size=pre_lookahead_len + 1,
  66. stride=1, padding=0,
  67. )
  68. self.conv2 = nn.Conv1d(
  69. channels, in_channels,
  70. kernel_size=3, stride=1, padding=0,
  71. )
  72. def forward(self, inputs: torch.Tensor, context: torch.Tensor = torch.zeros(0, 0, 0)) -> torch.Tensor:
  73. """
  74. inputs: (batch_size, seq_len, channels)
  75. """
  76. outputs = inputs.transpose(1, 2).contiguous()
  77. context = context.transpose(1, 2).contiguous()
  78. # look ahead
  79. if context.size(2) == 0:
  80. outputs = F.pad(outputs, (0, self.pre_lookahead_len), mode='constant', value=0.0)
  81. else:
  82. assert self.training is False, 'you have passed context, make sure that you are running inference mode'
  83. assert context.size(2) == self.pre_lookahead_len
  84. outputs = F.pad(torch.concat([outputs, context], dim=2), (0, self.pre_lookahead_len - context.size(2)), mode='constant', value=0.0)
  85. outputs = F.leaky_relu(self.conv1(outputs))
  86. # outputs
  87. outputs = F.pad(outputs, (self.conv2.kernel_size[0] - 1, 0), mode='constant', value=0.0)
  88. outputs = self.conv2(outputs)
  89. outputs = outputs.transpose(1, 2).contiguous()
  90. # residual connection
  91. outputs = outputs + inputs
  92. return outputs
  93. class UpsampleConformerEncoder(torch.nn.Module):
  94. def __init__(
  95. self,
  96. input_size: int,
  97. output_size: int = 256,
  98. attention_heads: int = 4,
  99. linear_units: int = 2048,
  100. num_blocks: int = 6,
  101. dropout_rate: float = 0.1,
  102. positional_dropout_rate: float = 0.1,
  103. attention_dropout_rate: float = 0.0,
  104. input_layer: str = "conv2d",
  105. pos_enc_layer_type: str = "rel_pos",
  106. normalize_before: bool = True,
  107. static_chunk_size: int = 0,
  108. use_dynamic_chunk: bool = False,
  109. global_cmvn: torch.nn.Module = None,
  110. use_dynamic_left_chunk: bool = False,
  111. positionwise_conv_kernel_size: int = 1,
  112. macaron_style: bool = True,
  113. selfattention_layer_type: str = "rel_selfattn",
  114. activation_type: str = "swish",
  115. use_cnn_module: bool = True,
  116. cnn_module_kernel: int = 15,
  117. causal: bool = False,
  118. cnn_module_norm: str = "batch_norm",
  119. key_bias: bool = True,
  120. gradient_checkpointing: bool = False,
  121. ):
  122. """
  123. Args:
  124. input_size (int): input dim
  125. output_size (int): dimension of attention
  126. attention_heads (int): the number of heads of multi head attention
  127. linear_units (int): the hidden units number of position-wise feed
  128. forward
  129. num_blocks (int): the number of decoder blocks
  130. dropout_rate (float): dropout rate
  131. attention_dropout_rate (float): dropout rate in attention
  132. positional_dropout_rate (float): dropout rate after adding
  133. positional encoding
  134. input_layer (str): input layer type.
  135. optional [linear, conv2d, conv2d6, conv2d8]
  136. pos_enc_layer_type (str): Encoder positional encoding layer type.
  137. opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos]
  138. normalize_before (bool):
  139. True: use layer_norm before each sub-block of a layer.
  140. False: use layer_norm after each sub-block of a layer.
  141. static_chunk_size (int): chunk size for static chunk training and
  142. decoding
  143. use_dynamic_chunk (bool): whether use dynamic chunk size for
  144. training or not, You can only use fixed chunk(chunk_size > 0)
  145. or dyanmic chunk size(use_dynamic_chunk = True)
  146. global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module
  147. use_dynamic_left_chunk (bool): whether use dynamic left chunk in
  148. dynamic chunk training
  149. key_bias: whether use bias in attention.linear_k, False for whisper models.
  150. gradient_checkpointing: rerunning a forward-pass segment for each
  151. checkpointed segment during backward.
  152. """
  153. super().__init__()
  154. self._output_size = output_size
  155. self.global_cmvn = global_cmvn
  156. self.embed = COSYVOICE_SUBSAMPLE_CLASSES[input_layer](
  157. input_size,
  158. output_size,
  159. dropout_rate,
  160. COSYVOICE_EMB_CLASSES[pos_enc_layer_type](output_size,
  161. positional_dropout_rate),
  162. )
  163. self.normalize_before = normalize_before
  164. self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5)
  165. self.static_chunk_size = static_chunk_size
  166. self.use_dynamic_chunk = use_dynamic_chunk
  167. self.use_dynamic_left_chunk = use_dynamic_left_chunk
  168. self.gradient_checkpointing = gradient_checkpointing
  169. activation = COSYVOICE_ACTIVATION_CLASSES[activation_type]()
  170. # self-attention module definition
  171. encoder_selfattn_layer_args = (
  172. attention_heads,
  173. output_size,
  174. attention_dropout_rate,
  175. key_bias,
  176. )
  177. # feed-forward module definition
  178. positionwise_layer_args = (
  179. output_size,
  180. linear_units,
  181. dropout_rate,
  182. activation,
  183. )
  184. # convolution module definition
  185. convolution_layer_args = (output_size, cnn_module_kernel, activation,
  186. cnn_module_norm, causal)
  187. self.pre_lookahead_layer = PreLookaheadLayer(in_channels=512, channels=512, pre_lookahead_len=3)
  188. self.encoders = torch.nn.ModuleList([
  189. ConformerEncoderLayer(
  190. output_size,
  191. COSYVOICE_ATTENTION_CLASSES[selfattention_layer_type](
  192. *encoder_selfattn_layer_args),
  193. PositionwiseFeedForward(*positionwise_layer_args),
  194. PositionwiseFeedForward(
  195. *positionwise_layer_args) if macaron_style else None,
  196. ConvolutionModule(
  197. *convolution_layer_args) if use_cnn_module else None,
  198. dropout_rate,
  199. normalize_before,
  200. ) for _ in range(num_blocks)
  201. ])
  202. self.up_layer = Upsample1D(channels=512, out_channels=512, stride=2)
  203. self.up_embed = COSYVOICE_SUBSAMPLE_CLASSES[input_layer](
  204. input_size,
  205. output_size,
  206. dropout_rate,
  207. COSYVOICE_EMB_CLASSES[pos_enc_layer_type](output_size,
  208. positional_dropout_rate),
  209. )
  210. self.up_encoders = torch.nn.ModuleList([
  211. ConformerEncoderLayer(
  212. output_size,
  213. COSYVOICE_ATTENTION_CLASSES[selfattention_layer_type](
  214. *encoder_selfattn_layer_args),
  215. PositionwiseFeedForward(*positionwise_layer_args),
  216. PositionwiseFeedForward(
  217. *positionwise_layer_args) if macaron_style else None,
  218. ConvolutionModule(
  219. *convolution_layer_args) if use_cnn_module else None,
  220. dropout_rate,
  221. normalize_before,
  222. ) for _ in range(4)
  223. ])
  224. def output_size(self) -> int:
  225. return self._output_size
  226. def forward(
  227. self,
  228. xs: torch.Tensor,
  229. xs_lens: torch.Tensor,
  230. context: torch.Tensor = torch.zeros(0, 0, 0),
  231. decoding_chunk_size: int = 0,
  232. num_decoding_left_chunks: int = -1,
  233. streaming: bool = False,
  234. ) -> Tuple[torch.Tensor, torch.Tensor]:
  235. """Embed positions in tensor.
  236. Args:
  237. xs: padded input tensor (B, T, D)
  238. xs_lens: input length (B)
  239. decoding_chunk_size: decoding chunk size for dynamic chunk
  240. 0: default for training, use random dynamic chunk.
  241. <0: for decoding, use full chunk.
  242. >0: for decoding, use fixed chunk size as set.
  243. num_decoding_left_chunks: number of left chunks, this is for decoding,
  244. the chunk size is decoding_chunk_size.
  245. >=0: use num_decoding_left_chunks
  246. <0: use all left chunks
  247. Returns:
  248. encoder output tensor xs, and subsampled masks
  249. xs: padded output tensor (B, T' ~= T/subsample_rate, D)
  250. masks: torch.Tensor batch padding mask after subsample
  251. (B, 1, T' ~= T/subsample_rate)
  252. NOTE(xcsong):
  253. We pass the `__call__` method of the modules instead of `forward` to the
  254. checkpointing API because `__call__` attaches all the hooks of the module.
  255. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2
  256. """
  257. T = xs.size(1)
  258. masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)
  259. if self.global_cmvn is not None:
  260. xs = self.global_cmvn(xs)
  261. xs, pos_emb, masks = self.embed(xs, masks)
  262. if context.size(1) != 0:
  263. assert self.training is False, 'you have passed context, make sure that you are running inference mode'
  264. context_masks = torch.ones(1, 1, context.size(1)).to(masks)
  265. context, _, _ = self.embed(context, context_masks, offset=xs.size(1))
  266. mask_pad = masks # (B, 1, T/subsample_rate)
  267. chunk_masks = add_optional_chunk_mask(xs, masks, False, False, 0, self.static_chunk_size if streaming is True else 0, -1)
  268. # lookahead + conformer encoder
  269. xs = self.pre_lookahead_layer(xs, context=context)
  270. xs = self.forward_layers(xs, chunk_masks, pos_emb, mask_pad)
  271. # upsample + conformer encoder
  272. xs = xs.transpose(1, 2).contiguous()
  273. xs, xs_lens = self.up_layer(xs, xs_lens)
  274. xs = xs.transpose(1, 2).contiguous()
  275. T = xs.size(1)
  276. masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)
  277. xs, pos_emb, masks = self.up_embed(xs, masks)
  278. mask_pad = masks # (B, 1, T/subsample_rate)
  279. chunk_masks = add_optional_chunk_mask(xs, masks, False, False, 0, self.static_chunk_size * self.up_layer.stride if streaming is True else 0, -1)
  280. xs = self.forward_up_layers(xs, chunk_masks, pos_emb, mask_pad)
  281. if self.normalize_before:
  282. xs = self.after_norm(xs)
  283. # Here we assume the mask is not changed in encoder layers, so just
  284. # return the masks before encoder layers, and the masks will be used
  285. # for cross attention with decoder later
  286. return xs, masks
  287. def forward_layers(self, xs: torch.Tensor, chunk_masks: torch.Tensor,
  288. pos_emb: torch.Tensor,
  289. mask_pad: torch.Tensor) -> torch.Tensor:
  290. for layer in self.encoders:
  291. xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
  292. return xs
  293. def forward_up_layers(self, xs: torch.Tensor, chunk_masks: torch.Tensor,
  294. pos_emb: torch.Tensor,
  295. mask_pad: torch.Tensor) -> torch.Tensor:
  296. for layer in self.up_encoders:
  297. xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
  298. return xs