owensong commited on
Commit
6c71dc6
·
verified ·
1 Parent(s): a079c2a

Remove obsolete package file tiny_tts/nn/attentions.py

Browse files
Files changed (1) hide show
  1. tiny_tts/nn/attentions.py +0 -424
tiny_tts/nn/attentions.py DELETED
@@ -1,424 +0,0 @@
1
- import math
2
- import torch
3
- from torch import nn
4
- from torch.nn import functional as F
5
-
6
- from . import commons
7
- import logging
8
-
9
- logger = logging.getLogger(__name__)
10
-
11
-
12
- class ChannelLayerNorm(nn.Module):
13
- def __init__(self, channels, eps=1e-5):
14
- super().__init__()
15
- self.channels = channels
16
- self.eps = eps
17
-
18
- self.gamma = nn.Parameter(torch.ones(channels))
19
- self.beta = nn.Parameter(torch.zeros(channels))
20
-
21
- def forward(self, x):
22
- x = x.transpose(1, -1)
23
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
24
- return x.transpose(1, -1)
25
-
26
-
27
- @torch.jit.script
28
- def gated_activation(input_a, input_b, n_channels):
29
- n_channels_int = n_channels[0]
30
- in_act = input_a + input_b
31
- t_act = torch.tanh(in_act[:, :n_channels_int, :])
32
- s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
33
- acts = t_act * s_act
34
- return acts
35
-
36
-
37
- class TransformerBlock(nn.Module):
38
- def __init__(
39
- self,
40
- hidden_channels,
41
- filter_channels,
42
- n_heads,
43
- n_layers,
44
- kernel_size=1,
45
- p_dropout=0.0,
46
- window_size=4,
47
- isflow=True,
48
- **kwargs
49
- ):
50
- super().__init__()
51
- self.hidden_channels = hidden_channels
52
- self.filter_channels = filter_channels
53
- self.n_heads = n_heads
54
- self.n_layers = n_layers
55
- self.kernel_size = kernel_size
56
- self.p_dropout = p_dropout
57
- self.window_size = window_size
58
-
59
- self.cond_layer_idx = self.n_layers
60
- if "gin_channels" in kwargs:
61
- self.gin_channels = kwargs["gin_channels"]
62
- if self.gin_channels != 0:
63
- self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
64
- self.cond_layer_idx = (
65
- kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
66
- )
67
- assert (
68
- self.cond_layer_idx < self.n_layers
69
- ), "cond_layer_idx should be less than n_layers"
70
- self.drop = nn.Dropout(p_dropout)
71
- self.attn_layers = nn.ModuleList()
72
- self.norm_layers_1 = nn.ModuleList()
73
- self.ffn_layers = nn.ModuleList()
74
- self.norm_layers_2 = nn.ModuleList()
75
-
76
- for i in range(self.n_layers):
77
- self.attn_layers.append(
78
- MultiHeadSelfAttention(
79
- hidden_channels,
80
- hidden_channels,
81
- n_heads,
82
- p_dropout=p_dropout,
83
- window_size=window_size,
84
- )
85
- )
86
- self.norm_layers_1.append(ChannelLayerNorm(hidden_channels))
87
- self.ffn_layers.append(
88
- FeedForward(
89
- hidden_channels,
90
- hidden_channels,
91
- filter_channels,
92
- kernel_size,
93
- p_dropout=p_dropout,
94
- )
95
- )
96
- self.norm_layers_2.append(ChannelLayerNorm(hidden_channels))
97
-
98
- def forward(self, x, x_mask, g=None):
99
- attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
100
- x = x * x_mask
101
- for i in range(self.n_layers):
102
- if i == self.cond_layer_idx and g is not None:
103
- g = self.spk_emb_linear(g.transpose(1, 2))
104
- g = g.transpose(1, 2)
105
- x = x + g
106
- x = x * x_mask
107
- y = self.attn_layers[i](x, x, attn_mask)
108
- y = self.drop(y)
109
- x = self.norm_layers_1[i](x + y)
110
-
111
- y = self.ffn_layers[i](x, x_mask)
112
- y = self.drop(y)
113
- x = self.norm_layers_2[i](x + y)
114
- x = x * x_mask
115
- return x
116
-
117
-
118
- class TransformerDecoder(nn.Module):
119
- def __init__(
120
- self,
121
- hidden_channels,
122
- filter_channels,
123
- n_heads,
124
- n_layers,
125
- kernel_size=1,
126
- p_dropout=0.0,
127
- proximal_bias=False,
128
- proximal_init=True,
129
- **kwargs
130
- ):
131
- super().__init__()
132
- self.hidden_channels = hidden_channels
133
- self.filter_channels = filter_channels
134
- self.n_heads = n_heads
135
- self.n_layers = n_layers
136
- self.kernel_size = kernel_size
137
- self.p_dropout = p_dropout
138
- self.proximal_bias = proximal_bias
139
- self.proximal_init = proximal_init
140
-
141
- self.drop = nn.Dropout(p_dropout)
142
- self.self_attn_layers = nn.ModuleList()
143
- self.norm_layers_0 = nn.ModuleList()
144
- self.encdec_attn_layers = nn.ModuleList()
145
- self.norm_layers_1 = nn.ModuleList()
146
- self.ffn_layers = nn.ModuleList()
147
- self.norm_layers_2 = nn.ModuleList()
148
- for i in range(self.n_layers):
149
- self.self_attn_layers.append(
150
- MultiHeadSelfAttention(
151
- hidden_channels,
152
- hidden_channels,
153
- n_heads,
154
- p_dropout=p_dropout,
155
- proximal_bias=proximal_bias,
156
- proximal_init=proximal_init,
157
- )
158
- )
159
- self.norm_layers_0.append(ChannelLayerNorm(hidden_channels))
160
- self.encdec_attn_layers.append(
161
- MultiHeadSelfAttention(
162
- hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
163
- )
164
- )
165
- self.norm_layers_1.append(ChannelLayerNorm(hidden_channels))
166
- self.ffn_layers.append(
167
- FeedForward(
168
- hidden_channels,
169
- hidden_channels,
170
- filter_channels,
171
- kernel_size,
172
- p_dropout=p_dropout,
173
- causal=True,
174
- )
175
- )
176
- self.norm_layers_2.append(ChannelLayerNorm(hidden_channels))
177
-
178
- def forward(self, x, x_mask, h, h_mask):
179
- self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
180
- device=x.device, dtype=x.dtype
181
- )
182
- encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
183
- x = x * x_mask
184
- for i in range(self.n_layers):
185
- y = self.self_attn_layers[i](x, x, self_attn_mask)
186
- y = self.drop(y)
187
- x = self.norm_layers_0[i](x + y)
188
-
189
- y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
190
- y = self.drop(y)
191
- x = self.norm_layers_1[i](x + y)
192
-
193
- y = self.ffn_layers[i](x, x_mask)
194
- y = self.drop(y)
195
- x = self.norm_layers_2[i](x + y)
196
- x = x * x_mask
197
- return x
198
-
199
-
200
- class MultiHeadSelfAttention(nn.Module):
201
- def __init__(
202
- self,
203
- channels,
204
- out_channels,
205
- n_heads,
206
- p_dropout=0.0,
207
- window_size=None,
208
- heads_share=True,
209
- block_length=None,
210
- proximal_bias=False,
211
- proximal_init=False,
212
- ):
213
- super().__init__()
214
- assert channels % n_heads == 0
215
-
216
- self.channels = channels
217
- self.out_channels = out_channels
218
- self.n_heads = n_heads
219
- self.p_dropout = p_dropout
220
- self.window_size = window_size
221
- self.heads_share = heads_share
222
- self.block_length = block_length
223
- self.proximal_bias = proximal_bias
224
- self.proximal_init = proximal_init
225
- self.attn = None
226
-
227
- self.k_channels = channels // n_heads
228
- self.conv_q = nn.Conv1d(channels, channels, 1)
229
- self.conv_k = nn.Conv1d(channels, channels, 1)
230
- self.conv_v = nn.Conv1d(channels, channels, 1)
231
- self.conv_o = nn.Conv1d(channels, out_channels, 1)
232
- self.drop = nn.Dropout(p_dropout)
233
-
234
- if window_size is not None:
235
- n_heads_rel = 1 if heads_share else n_heads
236
- rel_stddev = self.k_channels**-0.5
237
- self.emb_rel_k = nn.Parameter(
238
- torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
239
- * rel_stddev
240
- )
241
- self.emb_rel_v = nn.Parameter(
242
- torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
243
- * rel_stddev
244
- )
245
-
246
- nn.init.xavier_uniform_(self.conv_q.weight)
247
- nn.init.xavier_uniform_(self.conv_k.weight)
248
- nn.init.xavier_uniform_(self.conv_v.weight)
249
- if proximal_init:
250
- with torch.no_grad():
251
- self.conv_k.weight.copy_(self.conv_q.weight)
252
- self.conv_k.bias.copy_(self.conv_q.bias)
253
-
254
- def forward(self, x, c, attn_mask=None):
255
- q = self.conv_q(x)
256
- k = self.conv_k(c)
257
- v = self.conv_v(c)
258
-
259
- x, self.attn = self.attention(q, k, v, mask=attn_mask)
260
-
261
- x = self.conv_o(x)
262
- return x
263
-
264
- def attention(self, query, key, value, mask=None):
265
- b, d, t_s, t_t = (*key.size(), query.size(2))
266
- query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
267
- key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
268
- value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
269
-
270
- scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
271
- if self.window_size is not None:
272
- assert (
273
- t_s == t_t
274
- ), "Relative attention is only available for self-attention."
275
- key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
276
- rel_logits = self._matmul_with_relative_keys(
277
- query / math.sqrt(self.k_channels), key_relative_embeddings
278
- )
279
- scores_local = self._relative_position_to_absolute_position(rel_logits)
280
- scores = scores + scores_local
281
- if self.proximal_bias:
282
- assert t_s == t_t, "Proximal bias is only available for self-attention."
283
- scores = scores + self._attention_bias_proximal(t_s).to(
284
- device=scores.device, dtype=scores.dtype
285
- )
286
- if mask is not None:
287
- scores = scores.masked_fill(mask == 0, -1e4)
288
- if self.block_length is not None:
289
- assert (
290
- t_s == t_t
291
- ), "Local attention is only available for self-attention."
292
- block_mask = (
293
- torch.ones_like(scores)
294
- .triu(-self.block_length)
295
- .tril(self.block_length)
296
- )
297
- scores = scores.masked_fill(block_mask == 0, -1e4)
298
- p_attn = F.softmax(scores, dim=-1)
299
- p_attn = self.drop(p_attn)
300
- output = torch.matmul(p_attn, value)
301
- if self.window_size is not None:
302
- relative_weights = self._absolute_position_to_relative_position(p_attn)
303
- value_relative_embeddings = self._get_relative_embeddings(
304
- self.emb_rel_v, t_s
305
- )
306
- output = output + self._matmul_with_relative_values(
307
- relative_weights, value_relative_embeddings
308
- )
309
- output = (
310
- output.transpose(2, 3).contiguous().view(b, d, t_t)
311
- )
312
- return output, p_attn
313
-
314
- def _matmul_with_relative_values(self, x, y):
315
- ret = torch.matmul(x, y.unsqueeze(0))
316
- return ret
317
-
318
- def _matmul_with_relative_keys(self, x, y):
319
- ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
320
- return ret
321
-
322
- def _get_relative_embeddings(self, relative_embeddings, length):
323
- 2 * self.window_size + 1
324
- pad_length = max(length - (self.window_size + 1), 0)
325
- slice_start_position = max((self.window_size + 1) - length, 0)
326
- slice_end_position = slice_start_position + 2 * length - 1
327
- if pad_length > 0:
328
- padded_relative_embeddings = F.pad(
329
- relative_embeddings,
330
- commons.flatten_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
331
- )
332
- else:
333
- padded_relative_embeddings = relative_embeddings
334
- used_relative_embeddings = padded_relative_embeddings[
335
- :, slice_start_position:slice_end_position
336
- ]
337
- return used_relative_embeddings
338
-
339
- def _relative_position_to_absolute_position(self, x):
340
- batch, heads, length, _ = x.size()
341
- x = F.pad(x, commons.flatten_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
342
-
343
- x_flat = x.view([batch, heads, length * 2 * length])
344
- x_flat = F.pad(
345
- x_flat, commons.flatten_pad_shape([[0, 0], [0, 0], [0, length - 1]])
346
- )
347
-
348
- x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
349
- :, :, :length, length - 1 :
350
- ]
351
- return x_final
352
-
353
- def _absolute_position_to_relative_position(self, x):
354
- batch, heads, length, _ = x.size()
355
- x = F.pad(
356
- x, commons.flatten_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
357
- )
358
- x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
359
- x_flat = F.pad(x_flat, commons.flatten_pad_shape([[0, 0], [0, 0], [length, 0]]))
360
- x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
361
- return x_final
362
-
363
- def _attention_bias_proximal(self, length):
364
- r = torch.arange(length, dtype=torch.float32)
365
- diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
366
- return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
367
-
368
-
369
- class FeedForward(nn.Module):
370
- def __init__(
371
- self,
372
- in_channels,
373
- out_channels,
374
- filter_channels,
375
- kernel_size,
376
- p_dropout=0.0,
377
- activation=None,
378
- causal=False,
379
- ):
380
- super().__init__()
381
- self.in_channels = in_channels
382
- self.out_channels = out_channels
383
- self.filter_channels = filter_channels
384
- self.kernel_size = kernel_size
385
- self.p_dropout = p_dropout
386
- self.activation = activation
387
- self.causal = causal
388
-
389
- if causal:
390
- self.padding = self._causal_padding
391
- else:
392
- self.padding = self._same_padding
393
-
394
- self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
395
- self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
396
- self.drop = nn.Dropout(p_dropout)
397
-
398
- def forward(self, x, x_mask):
399
- x = self.conv_1(self.padding(x * x_mask))
400
- if self.activation == "gelu":
401
- x = x * torch.sigmoid(1.702 * x)
402
- else:
403
- x = torch.relu(x)
404
- x = self.drop(x)
405
- x = self.conv_2(self.padding(x * x_mask))
406
- return x * x_mask
407
-
408
- def _causal_padding(self, x):
409
- if self.kernel_size == 1:
410
- return x
411
- pad_l = self.kernel_size - 1
412
- pad_r = 0
413
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
414
- x = F.pad(x, commons.flatten_pad_shape(padding))
415
- return x
416
-
417
- def _same_padding(self, x):
418
- if self.kernel_size == 1:
419
- return x
420
- pad_l = (self.kernel_size - 1) // 2
421
- pad_r = self.kernel_size // 2
422
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
423
- x = F.pad(x, commons.flatten_pad_shape(padding))
424
- return x