modeling_univnet.py 25 KB

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