layers.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # *****************************************************************************
  2. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. # * Neither the name of the NVIDIA CORPORATION nor the
  12. # names of its contributors may be used to endorse or promote products
  13. # derived from this software without specific prior written permission.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
  19. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. #
  26. # *****************************************************************************
  27. import torch
  28. import torch.nn.functional as F
  29. from librosa.filters import mel as librosa_mel_fn
  30. from common.audio_processing import (dynamic_range_compression,
  31. dynamic_range_decompression)
  32. from common.stft import STFT
  33. class LinearNorm(torch.nn.Module):
  34. def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
  35. super(LinearNorm, self).__init__()
  36. self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
  37. torch.nn.init.xavier_uniform_(
  38. self.linear_layer.weight,
  39. gain=torch.nn.init.calculate_gain(w_init_gain))
  40. def forward(self, x):
  41. return self.linear_layer(x)
  42. class ConvNorm(torch.nn.Module):
  43. def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
  44. padding=None, dilation=1, bias=True, w_init_gain='linear',
  45. batch_norm=False):
  46. super(ConvNorm, self).__init__()
  47. if padding is None:
  48. assert(kernel_size % 2 == 1)
  49. padding = int(dilation * (kernel_size - 1) / 2)
  50. self.conv = torch.nn.Conv1d(in_channels, out_channels,
  51. kernel_size=kernel_size, stride=stride,
  52. padding=padding, dilation=dilation,
  53. bias=bias)
  54. self.norm = torch.nn.BatchNorm1D(out_channels) if batch_norm else None
  55. torch.nn.init.xavier_uniform_(
  56. self.conv.weight,
  57. gain=torch.nn.init.calculate_gain(w_init_gain))
  58. def forward(self, signal):
  59. if self.norm is None:
  60. return self.conv(signal)
  61. else:
  62. return self.norm(self.conv(signal))
  63. class ConvReLUNorm(torch.nn.Module):
  64. def __init__(self, in_channels, out_channels, kernel_size=1, dropout=0.0):
  65. super(ConvReLUNorm, self).__init__()
  66. self.conv = torch.nn.Conv1d(in_channels, out_channels,
  67. kernel_size=kernel_size,
  68. padding=(kernel_size // 2))
  69. self.norm = torch.nn.LayerNorm(out_channels)
  70. self.dropout = torch.nn.Dropout(dropout)
  71. def forward(self, signal):
  72. out = F.relu(self.conv(signal))
  73. out = self.norm(out.transpose(1, 2)).transpose(1, 2).to(signal.dtype)
  74. return self.dropout(out)
  75. class TacotronSTFT(torch.nn.Module):
  76. def __init__(self, filter_length=1024, hop_length=256, win_length=1024,
  77. n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0,
  78. mel_fmax=8000.0):
  79. super(TacotronSTFT, self).__init__()
  80. self.n_mel_channels = n_mel_channels
  81. self.sampling_rate = sampling_rate
  82. self.stft_fn = STFT(filter_length, hop_length, win_length)
  83. mel_basis = librosa_mel_fn(
  84. sr=sampling_rate,
  85. n_fft=filter_length,
  86. n_mels=n_mel_channels,
  87. fmin=mel_fmin,
  88. fmax=mel_fmax
  89. )
  90. mel_basis = torch.from_numpy(mel_basis).float()
  91. self.register_buffer('mel_basis', mel_basis)
  92. def spectral_normalize(self, magnitudes):
  93. output = dynamic_range_compression(magnitudes)
  94. return output
  95. def spectral_de_normalize(self, magnitudes):
  96. output = dynamic_range_decompression(magnitudes)
  97. return output
  98. def mel_spectrogram(self, y):
  99. """Computes mel-spectrograms from a batch of waves
  100. PARAMS
  101. ------
  102. y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
  103. RETURNS
  104. -------
  105. mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
  106. """
  107. assert(torch.min(y.data) >= -1)
  108. assert(torch.max(y.data) <= 1)
  109. magnitudes, phases = self.stft_fn.transform(y)
  110. magnitudes = magnitudes.data
  111. mel_output = torch.matmul(self.mel_basis, magnitudes)
  112. mel_output = self.spectral_normalize(mel_output)
  113. return mel_output