sinc_conv.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/env python3
  2. # 2020, Technische Universität München; Ludwig Kürzinger
  3. # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  4. """Sinc convolutions."""
  5. import math
  6. import torch
  7. from typing import Union
  8. class LogCompression(torch.nn.Module):
  9. """Log Compression Activation.
  10. Activation function `log(abs(x) + 1)`.
  11. """
  12. def __init__(self):
  13. """Initialize."""
  14. super().__init__()
  15. def forward(self, x: torch.Tensor) -> torch.Tensor:
  16. """Forward.
  17. Applies the Log Compression function elementwise on tensor x.
  18. """
  19. return torch.log(torch.abs(x) + 1)
  20. class SincConv(torch.nn.Module):
  21. """Sinc Convolution.
  22. This module performs a convolution using Sinc filters in time domain as kernel.
  23. Sinc filters function as band passes in spectral domain.
  24. The filtering is done as a convolution in time domain, and no transformation
  25. to spectral domain is necessary.
  26. This implementation of the Sinc convolution is heavily inspired
  27. by Ravanelli et al. https://github.com/mravanelli/SincNet,
  28. and adapted for the ESpnet toolkit.
  29. Combine Sinc convolutions with a log compression activation function, as in:
  30. https://arxiv.org/abs/2010.07597
  31. Notes:
  32. Currently, the same filters are applied to all input channels.
  33. The windowing function is applied on the kernel to obtained a smoother filter,
  34. and not on the input values, which is different to traditional ASR.
  35. """
  36. def __init__(
  37. self,
  38. in_channels: int,
  39. out_channels: int,
  40. kernel_size: int,
  41. stride: int = 1,
  42. padding: int = 0,
  43. dilation: int = 1,
  44. window_func: str = "hamming",
  45. scale_type: str = "mel",
  46. fs: Union[int, float] = 16000,
  47. ):
  48. """Initialize Sinc convolutions.
  49. Args:
  50. in_channels: Number of input channels.
  51. out_channels: Number of output channels.
  52. kernel_size: Sinc filter kernel size (needs to be an odd number).
  53. stride: See torch.nn.functional.conv1d.
  54. padding: See torch.nn.functional.conv1d.
  55. dilation: See torch.nn.functional.conv1d.
  56. window_func: Window function on the filter, one of ["hamming", "none"].
  57. fs (str, int, float): Sample rate of the input data
  58. """
  59. super().__init__()
  60. window_funcs = {
  61. "none": self.none_window,
  62. "hamming": self.hamming_window,
  63. }
  64. if window_func not in window_funcs:
  65. raise NotImplementedError(
  66. f"Window function has to be one of {list(window_funcs.keys())}",
  67. )
  68. self.window_func = window_funcs[window_func]
  69. scale_choices = {
  70. "mel": MelScale,
  71. "bark": BarkScale,
  72. }
  73. if scale_type not in scale_choices:
  74. raise NotImplementedError(
  75. f"Scale has to be one of {list(scale_choices.keys())}",
  76. )
  77. self.scale = scale_choices[scale_type]
  78. self.in_channels = in_channels
  79. self.out_channels = out_channels
  80. self.kernel_size = kernel_size
  81. self.padding = padding
  82. self.dilation = dilation
  83. self.stride = stride
  84. self.fs = float(fs)
  85. if self.kernel_size % 2 == 0:
  86. raise ValueError("SincConv: Kernel size must be odd.")
  87. self.f = None
  88. N = self.kernel_size // 2
  89. self._x = 2 * math.pi * torch.linspace(1, N, N)
  90. self._window = self.window_func(torch.linspace(1, N, N))
  91. # init may get overwritten by E2E network,
  92. # but is still required to calculate output dim
  93. self.init_filters()
  94. @staticmethod
  95. def sinc(x: torch.Tensor) -> torch.Tensor:
  96. """Sinc function."""
  97. x2 = x + 1e-6
  98. return torch.sin(x2) / x2
  99. @staticmethod
  100. def none_window(x: torch.Tensor) -> torch.Tensor:
  101. """Identity-like windowing function."""
  102. return torch.ones_like(x)
  103. @staticmethod
  104. def hamming_window(x: torch.Tensor) -> torch.Tensor:
  105. """Hamming Windowing function."""
  106. L = 2 * x.size(0) + 1
  107. x = x.flip(0)
  108. return 0.54 - 0.46 * torch.cos(2.0 * math.pi * x / L)
  109. def init_filters(self):
  110. """Initialize filters with filterbank values."""
  111. f = self.scale.bank(self.out_channels, self.fs)
  112. f = torch.div(f, self.fs)
  113. self.f = torch.nn.Parameter(f, requires_grad=True)
  114. def _create_filters(self, device: str):
  115. """Calculate coefficients.
  116. This function (re-)calculates the filter convolutions coefficients.
  117. """
  118. f_mins = torch.abs(self.f[:, 0])
  119. f_maxs = torch.abs(self.f[:, 0]) + torch.abs(self.f[:, 1] - self.f[:, 0])
  120. self._x = self._x.to(device)
  121. self._window = self._window.to(device)
  122. f_mins_x = torch.matmul(f_mins.view(-1, 1), self._x.view(1, -1))
  123. f_maxs_x = torch.matmul(f_maxs.view(-1, 1), self._x.view(1, -1))
  124. kernel = (torch.sin(f_maxs_x) - torch.sin(f_mins_x)) / (0.5 * self._x)
  125. kernel = kernel * self._window
  126. kernel_left = kernel.flip(1)
  127. kernel_center = (2 * f_maxs - 2 * f_mins).unsqueeze(1)
  128. filters = torch.cat([kernel_left, kernel_center, kernel], dim=1)
  129. filters = filters.view(filters.size(0), 1, filters.size(1))
  130. self.sinc_filters = filters
  131. def forward(self, xs: torch.Tensor) -> torch.Tensor:
  132. """Sinc convolution forward function.
  133. Args:
  134. xs: Batch in form of torch.Tensor (B, C_in, D_in).
  135. Returns:
  136. xs: Batch in form of torch.Tensor (B, C_out, D_out).
  137. """
  138. self._create_filters(xs.device)
  139. xs = torch.nn.functional.conv1d(
  140. xs,
  141. self.sinc_filters,
  142. padding=self.padding,
  143. stride=self.stride,
  144. dilation=self.dilation,
  145. groups=self.in_channels,
  146. )
  147. return xs
  148. def get_odim(self, idim: int) -> int:
  149. """Obtain the output dimension of the filter."""
  150. D_out = idim + 2 * self.padding - self.dilation * (self.kernel_size - 1) - 1
  151. D_out = (D_out // self.stride) + 1
  152. return D_out
  153. class MelScale:
  154. """Mel frequency scale."""
  155. @staticmethod
  156. def convert(f):
  157. """Convert Hz to mel."""
  158. return 1125.0 * torch.log(torch.div(f, 700.0) + 1.0)
  159. @staticmethod
  160. def invert(x):
  161. """Convert mel to Hz."""
  162. return 700.0 * (torch.exp(torch.div(x, 1125.0)) - 1.0)
  163. @classmethod
  164. def bank(cls, channels: int, fs: float) -> torch.Tensor:
  165. """Obtain initialization values for the mel scale.
  166. Args:
  167. channels: Number of channels.
  168. fs: Sample rate.
  169. Returns:
  170. torch.Tensor: Filter start frequencíes.
  171. torch.Tensor: Filter stop frequencies.
  172. """
  173. # min and max bandpass edge frequencies
  174. min_frequency = torch.tensor(30.0)
  175. max_frequency = torch.tensor(fs * 0.5)
  176. frequencies = torch.linspace(
  177. cls.convert(min_frequency), cls.convert(max_frequency), channels + 2
  178. )
  179. frequencies = cls.invert(frequencies)
  180. f1, f2 = frequencies[:-2], frequencies[2:]
  181. return torch.stack([f1, f2], dim=1)
  182. class BarkScale:
  183. """Bark frequency scale.
  184. Has wider bandwidths at lower frequencies, see:
  185. Critical bandwidth: BARK
  186. Zwicker and Terhardt, 1980
  187. """
  188. @staticmethod
  189. def convert(f):
  190. """Convert Hz to Bark."""
  191. b = torch.div(f, 1000.0)
  192. b = torch.pow(b, 2.0) * 1.4
  193. b = torch.pow(b + 1.0, 0.69)
  194. return b * 75.0 + 25.0
  195. @staticmethod
  196. def invert(x):
  197. """Convert Bark to Hz."""
  198. f = torch.div(x - 25.0, 75.0)
  199. f = torch.pow(f, (1.0 / 0.69))
  200. f = torch.div(f - 1.0, 1.4)
  201. f = torch.pow(f, 0.5)
  202. return f * 1000.0
  203. @classmethod
  204. def bank(cls, channels: int, fs: float) -> torch.Tensor:
  205. """Obtain initialization values for the Bark scale.
  206. Args:
  207. channels: Number of channels.
  208. fs: Sample rate.
  209. Returns:
  210. torch.Tensor: Filter start frequencíes.
  211. torch.Tensor: Filter stop frequencíes.
  212. """
  213. # min and max BARK center frequencies by approximation
  214. min_center_frequency = torch.tensor(70.0)
  215. max_center_frequency = torch.tensor(fs * 0.45)
  216. center_frequencies = torch.linspace(
  217. cls.convert(min_center_frequency),
  218. cls.convert(max_center_frequency),
  219. channels,
  220. )
  221. center_frequencies = cls.invert(center_frequencies)
  222. f1 = center_frequencies - torch.div(cls.convert(center_frequencies), 2)
  223. f2 = center_frequencies + torch.div(cls.convert(center_frequencies), 2)
  224. return torch.stack([f1, f2], dim=1)