Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

layers.py 13 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
  1. import math
  2. import torch
  3. from torch import nn
  4. from typing import Optional, Any
  5. from torch import Tensor
  6. import torch.nn.functional as F
  7. import torchaudio
  8. import torchaudio.functional as audio_F
  9. import random
  10. random.seed(0)
  11. def _get_activation_fn(activ):
  12. if activ == 'relu':
  13. return nn.ReLU()
  14. elif activ == 'lrelu':
  15. return nn.LeakyReLU(0.2)
  16. elif activ == 'swish':
  17. return lambda x: x*torch.sigmoid(x)
  18. else:
  19. raise RuntimeError('Unexpected activ type %s, expected [relu, lrelu, swish]' % activ)
  20. class LinearNorm(torch.nn.Module):
  21. def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
  22. super(LinearNorm, self).__init__()
  23. self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
  24. torch.nn.init.xavier_uniform_(
  25. self.linear_layer.weight,
  26. gain=torch.nn.init.calculate_gain(w_init_gain))
  27. def forward(self, x):
  28. return self.linear_layer(x)
  29. class ConvNorm(torch.nn.Module):
  30. def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
  31. padding=None, dilation=1, bias=True, w_init_gain='linear', param=None):
  32. super(ConvNorm, self).__init__()
  33. if padding is None:
  34. assert(kernel_size % 2 == 1)
  35. padding = int(dilation * (kernel_size - 1) / 2)
  36. self.conv = torch.nn.Conv1d(in_channels, out_channels,
  37. kernel_size=kernel_size, stride=stride,
  38. padding=padding, dilation=dilation,
  39. bias=bias)
  40. torch.nn.init.xavier_uniform_(
  41. self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain, param=param))
  42. def forward(self, signal):
  43. conv_signal = self.conv(signal)
  44. return conv_signal
  45. class CausualConv(nn.Module):
  46. def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=1, dilation=1, bias=True, w_init_gain='linear', param=None):
  47. super(CausualConv, self).__init__()
  48. if padding is None:
  49. assert(kernel_size % 2 == 1)
  50. padding = int(dilation * (kernel_size - 1) / 2) * 2
  51. else:
  52. self.padding = padding * 2
  53. self.conv = nn.Conv1d(in_channels, out_channels,
  54. kernel_size=kernel_size, stride=stride,
  55. padding=self.padding,
  56. dilation=dilation,
  57. bias=bias)
  58. torch.nn.init.xavier_uniform_(
  59. self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain, param=param))
  60. def forward(self, x):
  61. x = self.conv(x)
  62. x = x[:, :, :-self.padding]
  63. return x
  64. class CausualBlock(nn.Module):
  65. def __init__(self, hidden_dim, n_conv=3, dropout_p=0.2, activ='lrelu'):
  66. super(CausualBlock, self).__init__()
  67. self.blocks = nn.ModuleList([
  68. self._get_conv(hidden_dim, dilation=3**i, activ=activ, dropout_p=dropout_p)
  69. for i in range(n_conv)])
  70. def forward(self, x):
  71. for block in self.blocks:
  72. res = x
  73. x = block(x)
  74. x += res
  75. return x
  76. def _get_conv(self, hidden_dim, dilation, activ='lrelu', dropout_p=0.2):
  77. layers = [
  78. CausualConv(hidden_dim, hidden_dim, kernel_size=3, padding=dilation, dilation=dilation),
  79. _get_activation_fn(activ),
  80. nn.BatchNorm1d(hidden_dim),
  81. nn.Dropout(p=dropout_p),
  82. CausualConv(hidden_dim, hidden_dim, kernel_size=3, padding=1, dilation=1),
  83. _get_activation_fn(activ),
  84. nn.Dropout(p=dropout_p)
  85. ]
  86. return nn.Sequential(*layers)
  87. class ConvBlock(nn.Module):
  88. def __init__(self, hidden_dim, n_conv=3, dropout_p=0.2, activ='relu'):
  89. super().__init__()
  90. self._n_groups = 8
  91. self.blocks = nn.ModuleList([
  92. self._get_conv(hidden_dim, dilation=3**i, activ=activ, dropout_p=dropout_p)
  93. for i in range(n_conv)])
  94. def forward(self, x):
  95. for block in self.blocks:
  96. res = x
  97. x = block(x)
  98. x += res
  99. return x
  100. def _get_conv(self, hidden_dim, dilation, activ='relu', dropout_p=0.2):
  101. layers = [
  102. ConvNorm(hidden_dim, hidden_dim, kernel_size=3, padding=dilation, dilation=dilation),
  103. _get_activation_fn(activ),
  104. nn.GroupNorm(num_groups=self._n_groups, num_channels=hidden_dim),
  105. nn.Dropout(p=dropout_p),
  106. ConvNorm(hidden_dim, hidden_dim, kernel_size=3, padding=1, dilation=1),
  107. _get_activation_fn(activ),
  108. nn.Dropout(p=dropout_p)
  109. ]
  110. return nn.Sequential(*layers)
  111. class LocationLayer(nn.Module):
  112. def __init__(self, attention_n_filters, attention_kernel_size,
  113. attention_dim):
  114. super(LocationLayer, self).__init__()
  115. padding = int((attention_kernel_size - 1) / 2)
  116. self.location_conv = ConvNorm(2, attention_n_filters,
  117. kernel_size=attention_kernel_size,
  118. padding=padding, bias=False, stride=1,
  119. dilation=1)
  120. self.location_dense = LinearNorm(attention_n_filters, attention_dim,
  121. bias=False, w_init_gain='tanh')
  122. def forward(self, attention_weights_cat):
  123. processed_attention = self.location_conv(attention_weights_cat)
  124. processed_attention = processed_attention.transpose(1, 2)
  125. processed_attention = self.location_dense(processed_attention)
  126. return processed_attention
  127. class Attention(nn.Module):
  128. def __init__(self, attention_rnn_dim, embedding_dim, attention_dim,
  129. attention_location_n_filters, attention_location_kernel_size):
  130. super(Attention, self).__init__()
  131. self.query_layer = LinearNorm(attention_rnn_dim, attention_dim,
  132. bias=False, w_init_gain='tanh')
  133. self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False,
  134. w_init_gain='tanh')
  135. self.v = LinearNorm(attention_dim, 1, bias=False)
  136. self.location_layer = LocationLayer(attention_location_n_filters,
  137. attention_location_kernel_size,
  138. attention_dim)
  139. self.score_mask_value = -float("inf")
  140. def get_alignment_energies(self, query, processed_memory,
  141. attention_weights_cat):
  142. """
  143. PARAMS
  144. ------
  145. query: decoder output (batch, n_mel_channels * n_frames_per_step)
  146. processed_memory: processed encoder outputs (B, T_in, attention_dim)
  147. attention_weights_cat: cumulative and prev. att weights (B, 2, max_time)
  148. RETURNS
  149. -------
  150. alignment (batch, max_time)
  151. """
  152. processed_query = self.query_layer(query.unsqueeze(1))
  153. processed_attention_weights = self.location_layer(attention_weights_cat)
  154. energies = self.v(torch.tanh(
  155. processed_query + processed_attention_weights + processed_memory))
  156. energies = energies.squeeze(-1)
  157. return energies
  158. def forward(self, attention_hidden_state, memory, processed_memory,
  159. attention_weights_cat, mask):
  160. """
  161. PARAMS
  162. ------
  163. attention_hidden_state: attention rnn last output
  164. memory: encoder outputs
  165. processed_memory: processed encoder outputs
  166. attention_weights_cat: previous and cummulative attention weights
  167. mask: binary mask for padded data
  168. """
  169. alignment = self.get_alignment_energies(
  170. attention_hidden_state, processed_memory, attention_weights_cat)
  171. if mask is not None:
  172. alignment.data.masked_fill_(mask, self.score_mask_value)
  173. attention_weights = F.softmax(alignment, dim=1)
  174. attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)
  175. attention_context = attention_context.squeeze(1)
  176. return attention_context, attention_weights
  177. class ForwardAttentionV2(nn.Module):
  178. def __init__(self, attention_rnn_dim, embedding_dim, attention_dim,
  179. attention_location_n_filters, attention_location_kernel_size):
  180. super(ForwardAttentionV2, self).__init__()
  181. self.query_layer = LinearNorm(attention_rnn_dim, attention_dim,
  182. bias=False, w_init_gain='tanh')
  183. self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False,
  184. w_init_gain='tanh')
  185. self.v = LinearNorm(attention_dim, 1, bias=False)
  186. self.location_layer = LocationLayer(attention_location_n_filters,
  187. attention_location_kernel_size,
  188. attention_dim)
  189. self.score_mask_value = -float(1e20)
  190. def get_alignment_energies(self, query, processed_memory,
  191. attention_weights_cat):
  192. """
  193. PARAMS
  194. ------
  195. query: decoder output (batch, n_mel_channels * n_frames_per_step)
  196. processed_memory: processed encoder outputs (B, T_in, attention_dim)
  197. attention_weights_cat: prev. and cumulative att weights (B, 2, max_time)
  198. RETURNS
  199. -------
  200. alignment (batch, max_time)
  201. """
  202. processed_query = self.query_layer(query.unsqueeze(1))
  203. processed_attention_weights = self.location_layer(attention_weights_cat)
  204. energies = self.v(torch.tanh(
  205. processed_query + processed_attention_weights + processed_memory))
  206. energies = energies.squeeze(-1)
  207. return energies
  208. def forward(self, attention_hidden_state, memory, processed_memory,
  209. attention_weights_cat, mask, log_alpha):
  210. """
  211. PARAMS
  212. ------
  213. attention_hidden_state: attention rnn last output
  214. memory: encoder outputs
  215. processed_memory: processed encoder outputs
  216. attention_weights_cat: previous and cummulative attention weights
  217. mask: binary mask for padded data
  218. """
  219. log_energy = self.get_alignment_energies(
  220. attention_hidden_state, processed_memory, attention_weights_cat)
  221. #log_energy =
  222. if mask is not None:
  223. log_energy.data.masked_fill_(mask, self.score_mask_value)
  224. #attention_weights = F.softmax(alignment, dim=1)
  225. #content_score = log_energy.unsqueeze(1) #[B, MAX_TIME] -> [B, 1, MAX_TIME]
  226. #log_alpha = log_alpha.unsqueeze(2) #[B, MAX_TIME] -> [B, MAX_TIME, 1]
  227. #log_total_score = log_alpha + content_score
  228. #previous_attention_weights = attention_weights_cat[:,0,:]
  229. log_alpha_shift_padded = []
  230. max_time = log_energy.size(1)
  231. for sft in range(2):
  232. shifted = log_alpha[:,:max_time-sft]
  233. shift_padded = F.pad(shifted, (sft,0), 'constant', self.score_mask_value)
  234. log_alpha_shift_padded.append(shift_padded.unsqueeze(2))
  235. biased = torch.logsumexp(torch.cat(log_alpha_shift_padded,2), 2)
  236. log_alpha_new = biased + log_energy
  237. attention_weights = F.softmax(log_alpha_new, dim=1)
  238. attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)
  239. attention_context = attention_context.squeeze(1)
  240. return attention_context, attention_weights, log_alpha_new
  241. class PhaseShuffle2d(nn.Module):
  242. def __init__(self, n=2):
  243. super(PhaseShuffle2d, self).__init__()
  244. self.n = n
  245. self.random = random.Random(1)
  246. def forward(self, x, move=None):
  247. # x.size = (B, C, M, L)
  248. if move is None:
  249. move = self.random.randint(-self.n, self.n)
  250. if move == 0:
  251. return x
  252. else:
  253. left = x[:, :, :, :move]
  254. right = x[:, :, :, move:]
  255. shuffled = torch.cat([right, left], dim=3)
  256. return shuffled
  257. class PhaseShuffle1d(nn.Module):
  258. def __init__(self, n=2):
  259. super(PhaseShuffle1d, self).__init__()
  260. self.n = n
  261. self.random = random.Random(1)
  262. def forward(self, x, move=None):
  263. # x.size = (B, C, M, L)
  264. if move is None:
  265. move = self.random.randint(-self.n, self.n)
  266. if move == 0:
  267. return x
  268. else:
  269. left = x[:, :, :move]
  270. right = x[:, :, move:]
  271. shuffled = torch.cat([right, left], dim=2)
  272. return shuffled
  273. class MFCC(nn.Module):
  274. def __init__(self, n_mfcc=40, n_mels=80):
  275. super(MFCC, self).__init__()
  276. self.n_mfcc = n_mfcc
  277. self.n_mels = n_mels
  278. self.norm = 'ortho'
  279. dct_mat = audio_F.create_dct(self.n_mfcc, self.n_mels, self.norm)
  280. self.register_buffer('dct_mat', dct_mat)
  281. def forward(self, mel_specgram):
  282. if len(mel_specgram.shape) == 2:
  283. mel_specgram = mel_specgram.unsqueeze(0)
  284. unsqueezed = True
  285. else:
  286. unsqueezed = False
  287. # (channel, n_mels, time).tranpose(...) dot (n_mels, n_mfcc)
  288. # -> (channel, time, n_mfcc).tranpose(...)
  289. mfcc = torch.matmul(mel_specgram.transpose(1, 2), self.dct_mat).transpose(1, 2)
  290. # unpack batch
  291. if unsqueezed:
  292. mfcc = mfcc.squeeze(0)
  293. return mfcc
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...