modeling_univnet.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. # Copyright 2023 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTorch UnivNetModel model."""
  15. from dataclasses import dataclass
  16. from typing import Optional, Union
  17. import torch
  18. from torch import nn
  19. from ...modeling_outputs import ModelOutput
  20. from ...modeling_utils import PreTrainedModel
  21. from ...utils import auto_docstring, logging
  22. from .configuration_univnet import UnivNetConfig
  23. logger = logging.get_logger(__name__)
  24. @dataclass
  25. @auto_docstring(
  26. custom_intro="""
  27. Output class for the [`UnivNetModel`], which includes the generated audio waveforms and the original unpadded
  28. lengths of those waveforms (so that the padding can be removed by [`UnivNetModel.batch_decode`]).
  29. """
  30. )
  31. class UnivNetModelOutput(ModelOutput):
  32. r"""
  33. waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  34. Batched 1D (mono-channel) output audio waveforms.
  35. waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
  36. The batched length in samples of each unpadded waveform in `waveforms`.
  37. """
  38. waveforms: Optional[torch.FloatTensor] = None
  39. waveform_lengths: Optional[torch.FloatTensor] = None
  40. class UnivNetKernelPredictorResidualBlock(nn.Module):
  41. """
  42. Implementation of the residual block for the kernel predictor network inside each location variable convolution
  43. block (LVCBlock).
  44. Parameters:
  45. config: (`UnivNetConfig`):
  46. Config for the `UnivNetModel` model.
  47. """
  48. def __init__(
  49. self,
  50. config: UnivNetConfig,
  51. ):
  52. super().__init__()
  53. self.channels = config.model_in_channels
  54. self.kernel_size = config.kernel_predictor_conv_size
  55. self.dropout_prob = config.kernel_predictor_dropout
  56. self.leaky_relu_slope = config.leaky_relu_slope
  57. padding = (self.kernel_size - 1) // 2
  58. self.dropout = nn.Dropout(self.dropout_prob)
  59. self.conv1 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
  60. self.conv2 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
  61. def forward(self, hidden_states: torch.FloatTensor):
  62. # hidden_states should have shape (batch_size, channels, seq_length)
  63. residual = hidden_states
  64. hidden_states = self.dropout(hidden_states)
  65. hidden_states = self.conv1(hidden_states)
  66. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  67. hidden_states = self.conv2(hidden_states)
  68. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  69. return hidden_states + residual
  70. def apply_weight_norm(self):
  71. weight_norm = nn.utils.weight_norm
  72. if hasattr(nn.utils.parametrizations, "weight_norm"):
  73. weight_norm = nn.utils.parametrizations.weight_norm
  74. weight_norm(self.conv1)
  75. weight_norm(self.conv2)
  76. def remove_weight_norm(self):
  77. nn.utils.remove_weight_norm(self.conv1)
  78. nn.utils.remove_weight_norm(self.conv2)
  79. class UnivNetKernelPredictor(nn.Module):
  80. """
  81. Implementation of the kernel predictor network which supplies the kernel and bias for the location variable
  82. convolutional layers (LVCs) in each UnivNet LVCBlock.
  83. Based on the KernelPredictor implementation in
  84. [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L7).
  85. Parameters:
  86. config: (`UnivNetConfig`):
  87. Config for the `UnivNetModel` model.
  88. conv_kernel_size (`int`, *optional*, defaults to 3):
  89. The kernel size for the location variable convolutional layer kernels (convolutional weight tensor).
  90. conv_layers (`int`, *optional*, defaults to 4):
  91. The number of location variable convolutional layers to output kernels and biases for.
  92. """
  93. def __init__(
  94. self,
  95. config: UnivNetConfig,
  96. conv_kernel_size: int = 3,
  97. conv_layers: int = 4,
  98. ):
  99. super().__init__()
  100. self.conv_in_channels = config.model_hidden_channels
  101. self.conv_out_channels = 2 * config.model_hidden_channels
  102. self.conv_kernel_size = conv_kernel_size
  103. self.conv_layers = conv_layers
  104. self.kernel_channels = (
  105. self.conv_in_channels * self.conv_out_channels * self.conv_kernel_size * self.conv_layers
  106. )
  107. self.bias_channels = self.conv_out_channels * self.conv_layers
  108. self.resnet_in_channels = config.num_mel_bins
  109. self.resnet_hidden_channels = config.kernel_predictor_hidden_channels
  110. self.resnet_kernel_size = config.kernel_predictor_conv_size
  111. self.num_blocks = config.kernel_predictor_num_blocks
  112. self.leaky_relu_slope = config.leaky_relu_slope
  113. padding = (self.resnet_kernel_size - 1) // 2
  114. self.input_conv = nn.Conv1d(self.resnet_in_channels, self.resnet_hidden_channels, 5, padding=2, bias=True)
  115. self.resblocks = nn.ModuleList([UnivNetKernelPredictorResidualBlock(config) for _ in range(self.num_blocks)])
  116. self.kernel_conv = nn.Conv1d(
  117. self.resnet_hidden_channels, self.kernel_channels, self.resnet_kernel_size, padding=padding, bias=True
  118. )
  119. self.bias_conv = nn.Conv1d(
  120. self.resnet_hidden_channels, self.bias_channels, self.resnet_kernel_size, padding=padding, bias=True
  121. )
  122. def forward(self, spectrogram: torch.FloatTensor):
  123. """
  124. Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location
  125. variable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,
  126. seq_length).
  127. Args:
  128. spectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):
  129. Tensor containing the log-mel spectrograms.
  130. Returns:
  131. tuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of
  132. location variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,
  133. self.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of
  134. location variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,
  135. seq_length)`.
  136. """
  137. batch_size, _, seq_length = spectrogram.shape
  138. hidden_states = self.input_conv(spectrogram)
  139. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  140. for resblock in self.resblocks:
  141. hidden_states = resblock(hidden_states)
  142. kernel_hidden_states = self.kernel_conv(hidden_states)
  143. bias_hidden_states = self.bias_conv(hidden_states)
  144. # Reshape kernels and biases to appropriate shape
  145. kernels = kernel_hidden_states.view(
  146. batch_size,
  147. self.conv_layers,
  148. self.conv_in_channels,
  149. self.conv_out_channels,
  150. self.conv_kernel_size,
  151. seq_length,
  152. ).contiguous()
  153. biases = bias_hidden_states.view(
  154. batch_size,
  155. self.conv_layers,
  156. self.conv_out_channels,
  157. seq_length,
  158. ).contiguous()
  159. return kernels, biases
  160. def apply_weight_norm(self):
  161. weight_norm = nn.utils.weight_norm
  162. if hasattr(nn.utils.parametrizations, "weight_norm"):
  163. weight_norm = nn.utils.parametrizations.weight_norm
  164. weight_norm(self.input_conv)
  165. for layer in self.resblocks:
  166. layer.apply_weight_norm()
  167. weight_norm(self.kernel_conv)
  168. weight_norm(self.bias_conv)
  169. def remove_weight_norm(self):
  170. nn.utils.remove_weight_norm(self.input_conv)
  171. for layer in self.resblocks:
  172. layer.remove_weight_norm()
  173. nn.utils.remove_weight_norm(self.kernel_conv)
  174. nn.utils.remove_weight_norm(self.bias_conv)
  175. class UnivNetLvcResidualBlock(nn.Module):
  176. """
  177. Implementation of the location variable convolution (LVC) residual block for the UnivNet residual network.
  178. Parameters:
  179. config: (`UnivNetConfig`):
  180. Config for the `UnivNetModel` model.
  181. kernel_size (`int`):
  182. The kernel size for the dilated 1D convolutional layer.
  183. dilation (`int`):
  184. The dilation for the dilated 1D convolutional layer.
  185. """
  186. def __init__(
  187. self,
  188. config: UnivNetConfig,
  189. kernel_size: int,
  190. dilation: int,
  191. ):
  192. super().__init__()
  193. self.hidden_channels = config.model_hidden_channels
  194. self.kernel_size = kernel_size
  195. self.dilation = dilation
  196. self.leaky_relu_slope = config.leaky_relu_slope
  197. padding = self.dilation * (self.kernel_size - 1) // 2
  198. self.conv = nn.Conv1d(
  199. self.hidden_channels,
  200. self.hidden_channels,
  201. self.kernel_size,
  202. padding=padding,
  203. dilation=self.dilation,
  204. )
  205. def forward(self, hidden_states, kernel, bias, hop_size=256):
  206. residual = hidden_states
  207. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  208. hidden_states = self.conv(hidden_states)
  209. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  210. hidden_states = self.location_variable_convolution(hidden_states, kernel, bias, hop_size=hop_size)
  211. # Gated activation unit
  212. hidden_states = torch.sigmoid(hidden_states[:, : self.hidden_channels, :]) * torch.tanh(
  213. hidden_states[:, self.hidden_channels :, :]
  214. )
  215. # Skip connection
  216. hidden_states = residual + hidden_states
  217. return hidden_states
  218. # Based on https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L171
  219. def location_variable_convolution(
  220. self,
  221. hidden_states: torch.FloatTensor,
  222. kernel: torch.FloatTensor,
  223. bias: torch.FloatTensor,
  224. dilation: int = 1,
  225. hop_size: int = 256,
  226. ):
  227. """
  228. Performs location-variable convolution operation on the input sequence (hidden_states) using the local
  229. convolution kernel. This was introduced in [LVCNet: Efficient Condition-Dependent Modeling Network for Waveform
  230. Generation](https://huggingface.co/papers/2102.10815) by Zhen Zheng, Jianzong Wang, Ning Cheng, and Jing Xiao.
  231. Time: 414 μs ± 309 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each), test on NVIDIA V100.
  232. Args:
  233. hidden_states (`torch.FloatTensor` of shape `(batch_size, in_channels, in_length)`):
  234. The input sequence of shape (batch, in_channels, in_length).
  235. kernel (`torch.FloatTensor` of shape `(batch_size, in_channels, out_channels, kernel_size, kernel_length)`):
  236. The local convolution kernel of shape (batch, in_channels, out_channels, kernel_size, kernel_length).
  237. bias (`torch.FloatTensor` of shape `(batch_size, out_channels, kernel_length)`):
  238. The bias for the local convolution of shape (batch, out_channels, kernel_length).
  239. dilation (`int`, *optional*, defaults to 1):
  240. The dilation of convolution.
  241. hop_size (`int`, *optional*, defaults to 256):
  242. The hop_size of the conditioning sequence.
  243. Returns:
  244. `torch.FloatTensor`: the output sequence after performing local convolution with shape (batch_size,
  245. out_channels, in_length).
  246. """
  247. batch, _, in_length = hidden_states.shape
  248. batch, _, out_channels, kernel_size, kernel_length = kernel.shape
  249. if in_length != (kernel_length * hop_size):
  250. raise ValueError(
  251. f"Dim 2 of `hidden_states` should be {kernel_length * hop_size}) but got {in_length}. Please check"
  252. " `hidden_states` or `kernel` and `hop_size` to make sure they are correct."
  253. )
  254. padding = dilation * int((kernel_size - 1) / 2)
  255. # (batch, in_channels, in_length + 2*padding)
  256. hidden_states = nn.functional.pad(hidden_states, (padding, padding), "constant", 0)
  257. # (batch, in_channels, kernel_length, hop_size + 2*padding)
  258. hidden_states = hidden_states.unfold(2, hop_size + 2 * padding, hop_size)
  259. if hop_size < dilation:
  260. hidden_states = nn.functional.pad(hidden_states, (0, dilation), "constant", 0)
  261. # (batch, in_channels, kernel_length, (hop_size + 2*padding)/dilation, dilation)
  262. hidden_states = hidden_states.unfold(3, dilation, dilation)
  263. hidden_states = hidden_states[:, :, :, :, :hop_size]
  264. # (batch, in_channels, kernel_length, dilation, (hop_size + 2*padding)/dilation)
  265. hidden_states = hidden_states.transpose(3, 4)
  266. # (batch, in_channels, kernel_length, dilation, _, kernel_size)
  267. hidden_states = hidden_states.unfold(4, kernel_size, 1)
  268. # Apply local convolution kernel to hidden_states.
  269. output_hidden_states = torch.einsum("bildsk,biokl->bolsd", hidden_states, kernel)
  270. output_hidden_states = output_hidden_states.to(memory_format=torch.channels_last_3d)
  271. bias = bias.unsqueeze(-1).unsqueeze(-1).to(memory_format=torch.channels_last_3d)
  272. output_hidden_states = output_hidden_states + bias
  273. output_hidden_states = output_hidden_states.contiguous().view(batch, out_channels, -1)
  274. return output_hidden_states
  275. def apply_weight_norm(self):
  276. weight_norm = nn.utils.weight_norm
  277. if hasattr(nn.utils.parametrizations, "weight_norm"):
  278. weight_norm = nn.utils.parametrizations.weight_norm
  279. weight_norm(self.conv)
  280. def remove_weight_norm(self):
  281. nn.utils.remove_weight_norm(self.conv)
  282. class UnivNetLvcBlock(nn.Module):
  283. """
  284. Implementation of the location variable convolution (LVC) residual block of the UnivNet residual block. Includes a
  285. `UnivNetKernelPredictor` inside to predict the kernels and biases of the LVC layers.
  286. Based on LVCBlock in
  287. [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L98)
  288. Parameters:
  289. config (`UnivNetConfig`):
  290. Config for the `UnivNetModel` model.
  291. layer_id (`int`):
  292. An integer corresponding to the index of the current LVC resnet block layer. This should be between 0 and
  293. `len(config.resblock_stride_sizes) - 1)` inclusive.
  294. lvc_hop_size (`int`, *optional*, defaults to 256):
  295. The hop size for the location variable convolutional layers.
  296. """
  297. def __init__(
  298. self,
  299. config: UnivNetConfig,
  300. layer_id: int,
  301. lvc_hop_size: int = 256,
  302. ):
  303. super().__init__()
  304. self.hidden_channels = config.model_hidden_channels
  305. self.kernel_size = config.resblock_kernel_sizes[layer_id]
  306. self.stride = config.resblock_stride_sizes[layer_id]
  307. self.dilations = config.resblock_dilation_sizes[layer_id]
  308. self.cond_hop_length = lvc_hop_size
  309. self.leaky_relu_slope = config.leaky_relu_slope
  310. self.num_blocks = len(self.dilations)
  311. self.convt_pre = nn.ConvTranspose1d(
  312. self.hidden_channels,
  313. self.hidden_channels,
  314. 2 * self.stride,
  315. stride=self.stride,
  316. padding=self.stride // 2 + self.stride % 2,
  317. output_padding=self.stride % 2,
  318. )
  319. self.kernel_predictor = UnivNetKernelPredictor(config, self.kernel_size, self.num_blocks)
  320. self.resblocks = nn.ModuleList(
  321. [UnivNetLvcResidualBlock(config, self.kernel_size, self.dilations[i]) for i in range(self.num_blocks)]
  322. )
  323. def forward(self, hidden_states: torch.FloatTensor, spectrogram: torch.FloatTensor):
  324. # hidden_states: (batch_size, hidden_channels, seq_length)
  325. # spectrogram: (batch_size, cond_channels, cond_length)
  326. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  327. hidden_states = self.convt_pre(hidden_states)
  328. kernels, biases = self.kernel_predictor(spectrogram)
  329. for i, resblock in enumerate(self.resblocks):
  330. kernel = kernels[:, i, :, :, :, :]
  331. bias = biases[:, i, :, :]
  332. hidden_states = resblock(hidden_states, kernel, bias, hop_size=self.cond_hop_length)
  333. return hidden_states
  334. def apply_weight_norm(self):
  335. weight_norm = nn.utils.weight_norm
  336. if hasattr(nn.utils.parametrizations, "weight_norm"):
  337. weight_norm = nn.utils.parametrizations.weight_norm
  338. weight_norm(self.convt_pre)
  339. self.kernel_predictor.apply_weight_norm()
  340. for layer in self.resblocks:
  341. layer.apply_weight_norm()
  342. def remove_weight_norm(self):
  343. nn.utils.remove_weight_norm(self.convt_pre)
  344. self.kernel_predictor.remove_weight_norm()
  345. for layer in self.resblocks:
  346. layer.remove_weight_norm()
  347. @auto_docstring
  348. class UnivNetModel(PreTrainedModel):
  349. config: UnivNetConfig
  350. main_input_name = "input_features"
  351. def __init__(self, config: UnivNetConfig):
  352. super().__init__(config)
  353. self.num_kernels = len(config.resblock_kernel_sizes)
  354. self.leaky_relu_slope = config.leaky_relu_slope
  355. self.conv_pre = nn.Conv1d(
  356. config.model_in_channels,
  357. config.model_hidden_channels,
  358. kernel_size=7,
  359. stride=1,
  360. padding=3,
  361. padding_mode="reflect",
  362. )
  363. # Initialize location-variable convolution ResNet Blocks.
  364. num_layers = len(config.resblock_stride_sizes)
  365. hop_length = 1
  366. hop_lengths = []
  367. for stride in config.resblock_stride_sizes:
  368. hop_length = hop_length * stride
  369. hop_lengths.append(hop_length)
  370. self.resblocks = nn.ModuleList(
  371. [
  372. UnivNetLvcBlock(
  373. config,
  374. layer_id=i,
  375. lvc_hop_size=hop_lengths[i],
  376. )
  377. for i in range(num_layers)
  378. ]
  379. )
  380. self.conv_post = nn.Conv1d(config.model_hidden_channels, 1, 7, padding=3, padding_mode="reflect")
  381. # Initialize weights and apply final processing
  382. self.post_init()
  383. @auto_docstring
  384. def forward(
  385. self,
  386. input_features: torch.FloatTensor,
  387. noise_sequence: Optional[torch.FloatTensor] = None,
  388. padding_mask: Optional[torch.FloatTensor] = None,
  389. generator: Optional[torch.Generator] = None,
  390. return_dict: Optional[bool] = None,
  391. ) -> Union[tuple[torch.FloatTensor], UnivNetModelOutput]:
  392. r"""
  393. noise_sequence (`torch.FloatTensor`, *optional*):
  394. Tensor containing a noise sequence of standard Gaussian noise. Can be batched and of shape `(batch_size,
  395. sequence_length, config.model_in_channels)`, or un-batched and of shape (sequence_length,
  396. config.model_in_channels)`. If not supplied, will be randomly generated.
  397. padding_mask (`torch.BoolTensor`, *optional*):
  398. Mask indicating which parts of each sequence are padded. Mask values are selected in `[0, 1]`:
  399. - 1 for tokens that are **not masked**
  400. - 0 for tokens that are **masked**
  401. The mask can be batched and of shape `(batch_size, sequence_length)` or un-batched and of shape
  402. `(sequence_length,)`.
  403. generator (`torch.Generator`, *optional*):
  404. A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
  405. deterministic.
  406. return_dict:
  407. Whether to return a [`~utils.ModelOutput`] subclass instead of a plain tuple.
  408. Example:
  409. ```python
  410. >>> from transformers import UnivNetFeatureExtractor, UnivNetModel
  411. >>> from datasets import load_dataset, Audio
  412. >>> model = UnivNetModel.from_pretrained("dg845/univnet-dev")
  413. >>> feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev")
  414. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  415. >>> # Resample the audio to the feature extractor's sampling rate.
  416. >>> ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
  417. >>> inputs = feature_extractor(
  418. ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
  419. ... )
  420. >>> audio = model(**inputs).waveforms
  421. >>> list(audio.shape)
  422. [1, 140288]
  423. ```
  424. """
  425. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  426. # Resolve batch sizes for noise_sequence and spectrogram
  427. spectrogram_batched = input_features.dim() == 3
  428. if not spectrogram_batched:
  429. input_features = input_features.unsqueeze(0)
  430. spectrogram_batch_size, spectrogram_length, _ = input_features.shape
  431. if noise_sequence is not None:
  432. noise_sequence_batched = noise_sequence.dim() == 3
  433. if not noise_sequence_batched:
  434. noise_sequence = noise_sequence.unsqueeze(0)
  435. else:
  436. # Randomly generate noise_sequence
  437. noise_sequence_shape = (spectrogram_batch_size, spectrogram_length, self.config.model_in_channels)
  438. noise_sequence = torch.randn(
  439. noise_sequence_shape, generator=generator, dtype=input_features.dtype, device=input_features.device
  440. )
  441. noise_sequence_batch_size = noise_sequence.shape[0]
  442. if spectrogram_batch_size > 1 and noise_sequence_batch_size == 1:
  443. # Repeat noise_sequence spectrogram_batch_size times
  444. noise_sequence = noise_sequence.repeat(spectrogram_batch_size, 1, 1)
  445. elif noise_sequence_batch_size > 1 and spectrogram_batch_size == 1:
  446. # Repeat spectrogram noise_sequence_batch_size times
  447. input_features = input_features.repeat(noise_sequence_batch_size, 1, 1)
  448. if noise_sequence_batch_size != spectrogram_batch_size:
  449. raise ValueError(
  450. f"The batch size of `noise_sequence` is {noise_sequence_batch_size} and the batch size of"
  451. f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
  452. )
  453. if padding_mask is not None:
  454. if padding_mask.dim() == 1:
  455. padding_mask = padding_mask.unsqueeze(0)
  456. padding_mask_batch_size = padding_mask.shape[0]
  457. if padding_mask_batch_size != spectrogram_batch_size:
  458. raise ValueError(
  459. f"The batch size of `padding_mask` is {padding_mask_batch_size} and the batch size of"
  460. f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
  461. )
  462. # Change shapes to have channels before sequence lengths
  463. hidden_states = noise_sequence.transpose(2, 1)
  464. input_features = input_features.transpose(2, 1)
  465. hidden_states = self.conv_pre(hidden_states)
  466. for resblock in self.resblocks:
  467. hidden_states = resblock(hidden_states, input_features)
  468. hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
  469. hidden_states = self.conv_post(hidden_states)
  470. hidden_states = torch.tanh(hidden_states)
  471. # Remove sequence length dimension since this collapses to 1
  472. # NOTE: keep waveforms batched even if there's only one
  473. waveform = hidden_states.squeeze(1)
  474. # Get sequence lengths for UnivNetFeatureExtractor.batch_decode.
  475. waveform_lengths = None
  476. if padding_mask is not None:
  477. # Padding is always contiguous and added on the right
  478. waveform_lengths = torch.sum(padding_mask, dim=1)
  479. if not return_dict:
  480. outputs = (waveform, waveform_lengths)
  481. return outputs
  482. return UnivNetModelOutput(
  483. waveforms=waveform,
  484. waveform_lengths=waveform_lengths,
  485. )
  486. def _init_weights(self, module):
  487. """Initialize the weights."""
  488. if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)):
  489. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  490. if module.bias is not None:
  491. module.bias.data.zero_()
  492. def apply_weight_norm(self):
  493. weight_norm = nn.utils.weight_norm
  494. if hasattr(nn.utils.parametrizations, "weight_norm"):
  495. weight_norm = nn.utils.parametrizations.weight_norm
  496. weight_norm(self.conv_pre)
  497. for layer in self.resblocks:
  498. layer.apply_weight_norm()
  499. weight_norm(self.conv_post)
  500. def remove_weight_norm(self):
  501. nn.utils.remove_weight_norm(self.conv_pre)
  502. for layer in self.resblocks:
  503. layer.remove_weight_norm()
  504. nn.utils.remove_weight_norm(self.conv_post)
  505. __all__ = ["UnivNetModel"]