NeoPy commited on
Commit
a3e2a19
·
verified ·
1 Parent(s): 979717f

Create FCPE.py

Browse files
Files changed (1) hide show
  1. infer/lib/FCPE.py +920 -0
infer/lib/FCPE.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.nn.utils.parametrizations import weight_norm
8
+ from torchaudio.transforms import Resample
9
+ import os
10
+ import librosa
11
+ import soundfile as sf
12
+ import torch.utils.data
13
+ from librosa.filters import mel as librosa_mel_fn
14
+ import math
15
+ from functools import partial
16
+
17
+ from einops import rearrange, repeat
18
+ from local_attention import LocalAttention
19
+ from torch import nn
20
+
21
+ os.environ["LRU_CACHE_CAPACITY"] = "3"
22
+
23
+
24
+ def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
25
+ """Loads wav file to torch tensor."""
26
+ try:
27
+ data, sample_rate = sf.read(full_path, always_2d=True)
28
+ except Exception as error:
29
+ print(f"An error occurred loading {full_path}: {error}")
30
+ if return_empty_on_exception:
31
+ return [], sample_rate or target_sr or 48000
32
+ else:
33
+ raise
34
+
35
+ data = data[:, 0] if len(data.shape) > 1 else data
36
+ assert len(data) > 2
37
+
38
+ # Normalize data
39
+ max_mag = (
40
+ -np.iinfo(data.dtype).min
41
+ if np.issubdtype(data.dtype, np.integer)
42
+ else max(np.amax(data), -np.amin(data))
43
+ )
44
+ max_mag = (
45
+ (2**31) + 1 if max_mag > (2**15) else ((2**15) + 1 if max_mag > 1.01 else 1.0)
46
+ )
47
+ data = torch.FloatTensor(data.astype(np.float32)) / max_mag
48
+
49
+ # Handle exceptions and resample
50
+ if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:
51
+ return [], sample_rate or target_sr or 48000
52
+ if target_sr is not None and sample_rate != target_sr:
53
+ data = torch.from_numpy(
54
+ librosa.core.resample(
55
+ data.numpy(), orig_sr=sample_rate, target_sr=target_sr
56
+ )
57
+ )
58
+ sample_rate = target_sr
59
+
60
+ return data, sample_rate
61
+
62
+
63
+ def dynamic_range_compression(x, C=1, clip_val=1e-5):
64
+ return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
65
+
66
+
67
+ def dynamic_range_decompression(x, C=1):
68
+ return np.exp(x) / C
69
+
70
+
71
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
72
+ return torch.log(torch.clamp(x, min=clip_val) * C)
73
+
74
+
75
+ def dynamic_range_decompression_torch(x, C=1):
76
+ return torch.exp(x) / C
77
+
78
+
79
+ class STFT:
80
+ def __init__(
81
+ self,
82
+ sr=22050,
83
+ n_mels=80,
84
+ n_fft=1024,
85
+ win_size=1024,
86
+ hop_length=256,
87
+ fmin=20,
88
+ fmax=11025,
89
+ clip_val=1e-5,
90
+ ):
91
+ self.target_sr = sr
92
+ self.n_mels = n_mels
93
+ self.n_fft = n_fft
94
+ self.win_size = win_size
95
+ self.hop_length = hop_length
96
+ self.fmin = fmin
97
+ self.fmax = fmax
98
+ self.clip_val = clip_val
99
+ self.mel_basis = {}
100
+ self.hann_window = {}
101
+
102
+ def get_mel(self, y, keyshift=0, speed=1, center=False, train=False):
103
+ sample_rate = self.target_sr
104
+ n_mels = self.n_mels
105
+ n_fft = self.n_fft
106
+ win_size = self.win_size
107
+ hop_length = self.hop_length
108
+ fmin = self.fmin
109
+ fmax = self.fmax
110
+ clip_val = self.clip_val
111
+
112
+ factor = 2 ** (keyshift / 12)
113
+ n_fft_new = int(np.round(n_fft * factor))
114
+ win_size_new = int(np.round(win_size * factor))
115
+ hop_length_new = int(np.round(hop_length * speed))
116
+
117
+ # Optimize mel_basis and hann_window caching
118
+ mel_basis = self.mel_basis if not train else {}
119
+ hann_window = self.hann_window if not train else {}
120
+
121
+ mel_basis_key = str(fmax) + "_" + str(y.device)
122
+ if mel_basis_key not in mel_basis:
123
+ mel = librosa_mel_fn(
124
+ sr=sample_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax
125
+ )
126
+ mel_basis[mel_basis_key] = torch.from_numpy(mel).float().to(y.device)
127
+
128
+ keyshift_key = str(keyshift) + "_" + str(y.device)
129
+ if keyshift_key not in hann_window:
130
+ hann_window[keyshift_key] = torch.hann_window(win_size_new).to(y.device)
131
+
132
+ # Padding and STFT
133
+ pad_left = (win_size_new - hop_length_new) // 2
134
+ pad_right = max(
135
+ (win_size_new - hop_length_new + 1) // 2,
136
+ win_size_new - y.size(-1) - pad_left,
137
+ )
138
+ mode = "reflect" if pad_right < y.size(-1) else "constant"
139
+ y = torch.nn.functional.pad(y.unsqueeze(1), (pad_left, pad_right), mode=mode)
140
+ y = y.squeeze(1)
141
+
142
+ spec = torch.stft(
143
+ y,
144
+ n_fft=n_fft_new,
145
+ hop_length=hop_length_new,
146
+ win_length=win_size_new,
147
+ window=hann_window[keyshift_key],
148
+ center=center,
149
+ pad_mode="reflect",
150
+ normalized=False,
151
+ onesided=True,
152
+ return_complex=True,
153
+ )
154
+ spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + (1e-9))
155
+
156
+ # Handle keyshift and mel conversion
157
+ if keyshift != 0:
158
+ size = n_fft // 2 + 1
159
+ resize = spec.size(1)
160
+ spec = (
161
+ F.pad(spec, (0, 0, 0, size - resize))
162
+ if resize < size
163
+ else spec[:, :size, :]
164
+ )
165
+ spec = spec * win_size / win_size_new
166
+ spec = torch.matmul(mel_basis[mel_basis_key], spec)
167
+ spec = dynamic_range_compression_torch(spec, clip_val=clip_val)
168
+ return spec
169
+
170
+ def __call__(self, audiopath):
171
+ audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr)
172
+ spect = self.get_mel(audio.unsqueeze(0)).squeeze(0)
173
+ return spect
174
+
175
+
176
+ stft = STFT()
177
+
178
+
179
+ def softmax_kernel(
180
+ data, *, projection_matrix, is_query, normalize_data=True, eps=1e-4, device=None
181
+ ):
182
+ b, h, *_ = data.shape
183
+
184
+ # Normalize data
185
+ data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1.0
186
+
187
+ # Project data
188
+ ratio = projection_matrix.shape[0] ** -0.5
189
+ projection = repeat(projection_matrix, "j d -> b h j d", b=b, h=h)
190
+ projection = projection.type_as(data)
191
+ data_dash = torch.einsum("...id,...jd->...ij", (data_normalizer * data), projection)
192
+
193
+ # Calculate diagonal data
194
+ diag_data = data**2
195
+ diag_data = torch.sum(diag_data, dim=-1)
196
+ diag_data = (diag_data / 2.0) * (data_normalizer**2)
197
+ diag_data = diag_data.unsqueeze(dim=-1)
198
+
199
+ # Apply softmax
200
+ if is_query:
201
+ data_dash = ratio * (
202
+ torch.exp(
203
+ data_dash
204
+ - diag_data
205
+ - torch.max(data_dash, dim=-1, keepdim=True).values
206
+ )
207
+ + eps
208
+ )
209
+ else:
210
+ data_dash = ratio * (torch.exp(data_dash - diag_data + eps))
211
+
212
+ return data_dash.type_as(data)
213
+
214
+
215
+ def orthogonal_matrix_chunk(cols, qr_uniform_q=False, device=None):
216
+ unstructured_block = torch.randn((cols, cols), device=device)
217
+ q, r = torch.linalg.qr(unstructured_block.cpu(), mode="reduced")
218
+ q, r = map(lambda t: t.to(device), (q, r))
219
+
220
+ if qr_uniform_q:
221
+ d = torch.diag(r, 0)
222
+ q *= d.sign()
223
+ return q.t()
224
+
225
+
226
+ def exists(val):
227
+ return val is not None
228
+
229
+
230
+ def empty(tensor):
231
+ return tensor.numel() == 0
232
+
233
+
234
+ def default(val, d):
235
+ return val if exists(val) else d
236
+
237
+
238
+ def cast_tuple(val):
239
+ return (val,) if not isinstance(val, tuple) else val
240
+
241
+
242
+ class PCmer(nn.Module):
243
+ def __init__(
244
+ self,
245
+ num_layers,
246
+ num_heads,
247
+ dim_model,
248
+ dim_keys,
249
+ dim_values,
250
+ residual_dropout,
251
+ attention_dropout,
252
+ ):
253
+ super().__init__()
254
+ self.num_layers = num_layers
255
+ self.num_heads = num_heads
256
+ self.dim_model = dim_model
257
+ self.dim_values = dim_values
258
+ self.dim_keys = dim_keys
259
+ self.residual_dropout = residual_dropout
260
+ self.attention_dropout = attention_dropout
261
+
262
+ self._layers = nn.ModuleList([_EncoderLayer(self) for _ in range(num_layers)])
263
+
264
+ def forward(self, phone, mask=None):
265
+ for layer in self._layers:
266
+ phone = layer(phone, mask)
267
+ return phone
268
+
269
+
270
+ class _EncoderLayer(nn.Module):
271
+ def __init__(self, parent: PCmer):
272
+ super().__init__()
273
+ self.conformer = ConformerConvModule(parent.dim_model)
274
+ self.norm = nn.LayerNorm(parent.dim_model)
275
+ self.dropout = nn.Dropout(parent.residual_dropout)
276
+ self.attn = SelfAttention(
277
+ dim=parent.dim_model, heads=parent.num_heads, causal=False
278
+ )
279
+
280
+ def forward(self, phone, mask=None):
281
+ phone = phone + (self.attn(self.norm(phone), mask=mask))
282
+ phone = phone + (self.conformer(phone))
283
+ return phone
284
+
285
+
286
+ def calc_same_padding(kernel_size):
287
+ pad = kernel_size // 2
288
+ return (pad, pad - (kernel_size + 1) % 2)
289
+
290
+
291
+ class Swish(nn.Module):
292
+ def forward(self, x):
293
+ return x * x.sigmoid()
294
+
295
+
296
+ class Transpose(nn.Module):
297
+ def __init__(self, dims):
298
+ super().__init__()
299
+ assert len(dims) == 2, "dims must be a tuple of two dimensions"
300
+ self.dims = dims
301
+
302
+ def forward(self, x):
303
+ return x.transpose(*self.dims)
304
+
305
+
306
+ class GLU(nn.Module):
307
+ def __init__(self, dim):
308
+ super().__init__()
309
+ self.dim = dim
310
+
311
+ def forward(self, x):
312
+ out, gate = x.chunk(2, dim=self.dim)
313
+ return out * gate.sigmoid()
314
+
315
+
316
+ class DepthWiseConv1d(nn.Module):
317
+ def __init__(self, chan_in, chan_out, kernel_size, padding):
318
+ super().__init__()
319
+ self.padding = padding
320
+ self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, groups=chan_in)
321
+
322
+ def forward(self, x):
323
+ x = F.pad(x, self.padding)
324
+ return self.conv(x)
325
+
326
+
327
+ class ConformerConvModule(nn.Module):
328
+ def __init__(
329
+ self, dim, causal=False, expansion_factor=2, kernel_size=31, dropout=0.0
330
+ ):
331
+ super().__init__()
332
+
333
+ inner_dim = dim * expansion_factor
334
+ padding = calc_same_padding(kernel_size) if not causal else (kernel_size - 1, 0)
335
+
336
+ self.net = nn.Sequential(
337
+ nn.LayerNorm(dim),
338
+ Transpose((1, 2)),
339
+ nn.Conv1d(dim, inner_dim * 2, 1),
340
+ GLU(dim=1),
341
+ DepthWiseConv1d(
342
+ inner_dim, inner_dim, kernel_size=kernel_size, padding=padding
343
+ ),
344
+ Swish(),
345
+ nn.Conv1d(inner_dim, dim, 1),
346
+ Transpose((1, 2)),
347
+ nn.Dropout(dropout),
348
+ )
349
+
350
+ def forward(self, x):
351
+ return self.net(x)
352
+
353
+
354
+ def linear_attention(q, k, v):
355
+ if v is None:
356
+ out = torch.einsum("...ed,...nd->...ne", k, q)
357
+ return out
358
+ else:
359
+ k_cumsum = k.sum(dim=-2)
360
+ D_inv = 1.0 / (torch.einsum("...nd,...d->...n", q, k_cumsum.type_as(q)) + 1e-8)
361
+ context = torch.einsum("...nd,...ne->...de", k, v)
362
+ out = torch.einsum("...de,...nd,...n->...ne", context, q, D_inv)
363
+ return out
364
+
365
+
366
+ def gaussian_orthogonal_random_matrix(
367
+ nb_rows, nb_columns, scaling=0, qr_uniform_q=False, device=None
368
+ ):
369
+ nb_full_blocks = int(nb_rows / nb_columns)
370
+ block_list = []
371
+
372
+ for _ in range(nb_full_blocks):
373
+ q = orthogonal_matrix_chunk(
374
+ nb_columns, qr_uniform_q=qr_uniform_q, device=device
375
+ )
376
+ block_list.append(q)
377
+
378
+ remaining_rows = nb_rows - nb_full_blocks * nb_columns
379
+ if remaining_rows > 0:
380
+ q = orthogonal_matrix_chunk(
381
+ nb_columns, qr_uniform_q=qr_uniform_q, device=device
382
+ )
383
+ block_list.append(q[:remaining_rows])
384
+
385
+ final_matrix = torch.cat(block_list)
386
+
387
+ if scaling == 0:
388
+ multiplier = torch.randn((nb_rows, nb_columns), device=device).norm(dim=1)
389
+ elif scaling == 1:
390
+ multiplier = math.sqrt((float(nb_columns))) * torch.ones(
391
+ (nb_rows,), device=device
392
+ )
393
+ else:
394
+ raise ValueError(f"Invalid scaling {scaling}")
395
+
396
+ return torch.diag(multiplier) @ final_matrix
397
+
398
+
399
+ class FastAttention(nn.Module):
400
+ def __init__(
401
+ self,
402
+ dim_heads,
403
+ nb_features=None,
404
+ ortho_scaling=0,
405
+ causal=False,
406
+ generalized_attention=False,
407
+ kernel_fn=nn.ReLU(),
408
+ qr_uniform_q=False,
409
+ no_projection=False,
410
+ ):
411
+ super().__init__()
412
+ nb_features = default(nb_features, int(dim_heads * math.log(dim_heads)))
413
+
414
+ self.dim_heads = dim_heads
415
+ self.nb_features = nb_features
416
+ self.ortho_scaling = ortho_scaling
417
+
418
+ self.create_projection = partial(
419
+ gaussian_orthogonal_random_matrix,
420
+ nb_rows=self.nb_features,
421
+ nb_columns=dim_heads,
422
+ scaling=ortho_scaling,
423
+ qr_uniform_q=qr_uniform_q,
424
+ )
425
+ projection_matrix = self.create_projection()
426
+ self.register_buffer("projection_matrix", projection_matrix)
427
+
428
+ self.generalized_attention = generalized_attention
429
+ self.kernel_fn = kernel_fn
430
+ self.no_projection = no_projection
431
+ self.causal = causal
432
+
433
+ @torch.no_grad()
434
+ def redraw_projection_matrix(self):
435
+ projections = self.create_projection()
436
+ self.projection_matrix.copy_(projections)
437
+ del projections
438
+
439
+ def forward(self, q, k, v):
440
+ device = q.device
441
+
442
+ if self.no_projection:
443
+ q = q.softmax(dim=-1)
444
+ k = torch.exp(k) if self.causal else k.softmax(dim=-2)
445
+ else:
446
+ create_kernel = partial(
447
+ softmax_kernel, projection_matrix=self.projection_matrix, device=device
448
+ )
449
+ q = create_kernel(q, is_query=True)
450
+ k = create_kernel(k, is_query=False)
451
+
452
+ attn_fn = linear_attention if not self.causal else self.causal_linear_fn
453
+
454
+ if v is None:
455
+ out = attn_fn(q, k, None)
456
+ return out
457
+ else:
458
+ out = attn_fn(q, k, v)
459
+ return out
460
+
461
+
462
+ class SelfAttention(nn.Module):
463
+ def __init__(
464
+ self,
465
+ dim,
466
+ causal=False,
467
+ heads=8,
468
+ dim_head=64,
469
+ local_heads=0,
470
+ local_window_size=256,
471
+ nb_features=None,
472
+ feature_redraw_interval=1000,
473
+ generalized_attention=False,
474
+ kernel_fn=nn.ReLU(),
475
+ qr_uniform_q=False,
476
+ dropout=0.0,
477
+ no_projection=False,
478
+ ):
479
+ super().__init__()
480
+ assert dim % heads == 0, "dimension must be divisible by number of heads"
481
+ dim_head = default(dim_head, dim // heads)
482
+ inner_dim = dim_head * heads
483
+ self.fast_attention = FastAttention(
484
+ dim_head,
485
+ nb_features,
486
+ causal=causal,
487
+ generalized_attention=generalized_attention,
488
+ kernel_fn=kernel_fn,
489
+ qr_uniform_q=qr_uniform_q,
490
+ no_projection=no_projection,
491
+ )
492
+
493
+ self.heads = heads
494
+ self.global_heads = heads - local_heads
495
+ self.local_attn = (
496
+ LocalAttention(
497
+ window_size=local_window_size,
498
+ causal=causal,
499
+ autopad=True,
500
+ dropout=dropout,
501
+ look_forward=int(not causal),
502
+ rel_pos_emb_config=(dim_head, local_heads),
503
+ )
504
+ if local_heads > 0
505
+ else None
506
+ )
507
+
508
+ self.to_q = nn.Linear(dim, inner_dim)
509
+ self.to_k = nn.Linear(dim, inner_dim)
510
+ self.to_v = nn.Linear(dim, inner_dim)
511
+ self.to_out = nn.Linear(inner_dim, dim)
512
+ self.dropout = nn.Dropout(dropout)
513
+
514
+ @torch.no_grad()
515
+ def redraw_projection_matrix(self):
516
+ self.fast_attention.redraw_projection_matrix()
517
+
518
+ def forward(
519
+ self,
520
+ x,
521
+ context=None,
522
+ mask=None,
523
+ context_mask=None,
524
+ name=None,
525
+ inference=False,
526
+ **kwargs,
527
+ ):
528
+ _, _, _, h, gh = *x.shape, self.heads, self.global_heads
529
+
530
+ cross_attend = exists(context)
531
+ context = default(context, x)
532
+ context_mask = default(context_mask, mask) if not cross_attend else context_mask
533
+ q, k, v = self.to_q(x), self.to_k(context), self.to_v(context)
534
+
535
+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v))
536
+ (q, lq), (k, lk), (v, lv) = map(lambda t: (t[:, :gh], t[:, gh:]), (q, k, v))
537
+
538
+ attn_outs = []
539
+ if not empty(q):
540
+ if exists(context_mask):
541
+ global_mask = context_mask[:, None, :, None]
542
+ v.masked_fill_(~global_mask, 0.0)
543
+ if cross_attend:
544
+ pass # TODO: Implement cross-attention
545
+ else:
546
+ out = self.fast_attention(q, k, v)
547
+ attn_outs.append(out)
548
+
549
+ if not empty(lq):
550
+ assert (
551
+ not cross_attend
552
+ ), "local attention is not compatible with cross attention"
553
+ out = self.local_attn(lq, lk, lv, input_mask=mask)
554
+ attn_outs.append(out)
555
+
556
+ out = torch.cat(attn_outs, dim=1)
557
+ out = rearrange(out, "b h n d -> b n (h d)")
558
+ out = self.to_out(out)
559
+ return self.dropout(out)
560
+
561
+
562
+ def l2_regularization(model, l2_alpha):
563
+ l2_loss = []
564
+ for module in model.modules():
565
+ if type(module) is nn.Conv2d:
566
+ l2_loss.append((module.weight**2).sum() / 2.0)
567
+ return l2_alpha * sum(l2_loss)
568
+
569
+
570
+ class FCPE(nn.Module):
571
+ def __init__(
572
+ self,
573
+ input_channel=128,
574
+ out_dims=360,
575
+ n_layers=12,
576
+ n_chans=512,
577
+ use_siren=False,
578
+ use_full=False,
579
+ loss_mse_scale=10,
580
+ loss_l2_regularization=False,
581
+ loss_l2_regularization_scale=1,
582
+ loss_grad1_mse=False,
583
+ loss_grad1_mse_scale=1,
584
+ f0_max=1975.5,
585
+ f0_min=32.70,
586
+ confidence=False,
587
+ threshold=0.05,
588
+ use_input_conv=True,
589
+ ):
590
+ super().__init__()
591
+ if use_siren is True:
592
+ raise ValueError("Siren is not supported yet.")
593
+ if use_full is True:
594
+ raise ValueError("Full model is not supported yet.")
595
+
596
+ self.loss_mse_scale = loss_mse_scale if (loss_mse_scale is not None) else 10
597
+ self.loss_l2_regularization = (
598
+ loss_l2_regularization if (loss_l2_regularization is not None) else False
599
+ )
600
+ self.loss_l2_regularization_scale = (
601
+ loss_l2_regularization_scale
602
+ if (loss_l2_regularization_scale is not None)
603
+ else 1
604
+ )
605
+ self.loss_grad1_mse = loss_grad1_mse if (loss_grad1_mse is not None) else False
606
+ self.loss_grad1_mse_scale = (
607
+ loss_grad1_mse_scale if (loss_grad1_mse_scale is not None) else 1
608
+ )
609
+ self.f0_max = f0_max if (f0_max is not None) else 1975.5
610
+ self.f0_min = f0_min if (f0_min is not None) else 32.70
611
+ self.confidence = confidence if (confidence is not None) else False
612
+ self.threshold = threshold if (threshold is not None) else 0.05
613
+ self.use_input_conv = use_input_conv if (use_input_conv is not None) else True
614
+
615
+ self.cent_table_b = torch.Tensor(
616
+ np.linspace(
617
+ self.f0_to_cent(torch.Tensor([f0_min]))[0],
618
+ self.f0_to_cent(torch.Tensor([f0_max]))[0],
619
+ out_dims,
620
+ )
621
+ )
622
+ self.register_buffer("cent_table", self.cent_table_b)
623
+
624
+ # conv in stack
625
+ _leaky = nn.LeakyReLU()
626
+ self.stack = nn.Sequential(
627
+ nn.Conv1d(input_channel, n_chans, 3, 1, 1),
628
+ nn.GroupNorm(4, n_chans),
629
+ _leaky,
630
+ nn.Conv1d(n_chans, n_chans, 3, 1, 1),
631
+ )
632
+
633
+ # transformer
634
+ self.decoder = PCmer(
635
+ num_layers=n_layers,
636
+ num_heads=8,
637
+ dim_model=n_chans,
638
+ dim_keys=n_chans,
639
+ dim_values=n_chans,
640
+ residual_dropout=0.1,
641
+ attention_dropout=0.1,
642
+ )
643
+ self.norm = nn.LayerNorm(n_chans)
644
+
645
+ # out
646
+ self.n_out = out_dims
647
+ self.dense_out = weight_norm(nn.Linear(n_chans, self.n_out))
648
+
649
+ def forward(
650
+ self, mel, infer=True, gt_f0=None, return_hz_f0=False, cdecoder="local_argmax"
651
+ ):
652
+ if cdecoder == "argmax":
653
+ self.cdecoder = self.cents_decoder
654
+ elif cdecoder == "local_argmax":
655
+ self.cdecoder = self.cents_local_decoder
656
+
657
+ x = (
658
+ self.stack(mel.transpose(1, 2)).transpose(1, 2)
659
+ if self.use_input_conv
660
+ else mel
661
+ )
662
+ x = self.decoder(x)
663
+ x = self.norm(x)
664
+ x = self.dense_out(x)
665
+ x = torch.sigmoid(x)
666
+
667
+ if not infer:
668
+ gt_cent_f0 = self.f0_to_cent(gt_f0)
669
+ gt_cent_f0 = self.gaussian_blurred_cent(gt_cent_f0)
670
+ loss_all = self.loss_mse_scale * F.binary_cross_entropy(x, gt_cent_f0)
671
+ if self.loss_l2_regularization:
672
+ loss_all = loss_all + l2_regularization(
673
+ model=self, l2_alpha=self.loss_l2_regularization_scale
674
+ )
675
+ x = loss_all
676
+ if infer:
677
+ x = self.cdecoder(x)
678
+ x = self.cent_to_f0(x)
679
+ x = (1 + x / 700).log() if not return_hz_f0 else x
680
+
681
+ return x
682
+
683
+ def cents_decoder(self, y, mask=True):
684
+ B, N, _ = y.size()
685
+ ci = self.cent_table[None, None, :].expand(B, N, -1)
686
+ rtn = torch.sum(ci * y, dim=-1, keepdim=True) / torch.sum(
687
+ y, dim=-1, keepdim=True
688
+ )
689
+ if mask:
690
+ confident = torch.max(y, dim=-1, keepdim=True)[0]
691
+ confident_mask = torch.ones_like(confident)
692
+ confident_mask[confident <= self.threshold] = float("-INF")
693
+ rtn = rtn * confident_mask
694
+ return (rtn, confident) if self.confidence else rtn
695
+
696
+ def cents_local_decoder(self, y, mask=True):
697
+ B, N, _ = y.size()
698
+ ci = self.cent_table[None, None, :].expand(B, N, -1)
699
+ confident, max_index = torch.max(y, dim=-1, keepdim=True)
700
+ local_argmax_index = torch.arange(0, 9).to(max_index.device) + (max_index - 4)
701
+ local_argmax_index = torch.clamp(local_argmax_index, 0, self.n_out - 1)
702
+ ci_l = torch.gather(ci, -1, local_argmax_index)
703
+ y_l = torch.gather(y, -1, local_argmax_index)
704
+ rtn = torch.sum(ci_l * y_l, dim=-1, keepdim=True) / torch.sum(
705
+ y_l, dim=-1, keepdim=True
706
+ )
707
+ if mask:
708
+ confident_mask = torch.ones_like(confident)
709
+ confident_mask[confident <= self.threshold] = float("-INF")
710
+ rtn = rtn * confident_mask
711
+ return (rtn, confident) if self.confidence else rtn
712
+
713
+ def cent_to_f0(self, cent):
714
+ return 10.0 * 2 ** (cent / 1200.0)
715
+
716
+ def f0_to_cent(self, f0):
717
+ return 1200.0 * torch.log2(f0 / 10.0)
718
+
719
+ def gaussian_blurred_cent(self, cents):
720
+ mask = (cents > 0.1) & (cents < (1200.0 * np.log2(self.f0_max / 10.0)))
721
+ B, N, _ = cents.size()
722
+ ci = self.cent_table[None, None, :].expand(B, N, -1)
723
+ return torch.exp(-torch.square(ci - cents) / 1250) * mask.float()
724
+
725
+
726
+ class FCPEInfer:
727
+ def __init__(self, model_path, device=None, dtype=torch.float32):
728
+ if device is None:
729
+ device = "cuda" if torch.cuda.is_available() else "cpu"
730
+ self.device = device
731
+ ckpt = torch.load(
732
+ model_path, map_location=torch.device(self.device), weights_only=True
733
+ )
734
+ self.args = DotDict(ckpt["config"])
735
+ self.dtype = dtype
736
+ model = FCPE(
737
+ input_channel=self.args.model.input_channel,
738
+ out_dims=self.args.model.out_dims,
739
+ n_layers=self.args.model.n_layers,
740
+ n_chans=self.args.model.n_chans,
741
+ use_siren=self.args.model.use_siren,
742
+ use_full=self.args.model.use_full,
743
+ loss_mse_scale=self.args.loss.loss_mse_scale,
744
+ loss_l2_regularization=self.args.loss.loss_l2_regularization,
745
+ loss_l2_regularization_scale=self.args.loss.loss_l2_regularization_scale,
746
+ loss_grad1_mse=self.args.loss.loss_grad1_mse,
747
+ loss_grad1_mse_scale=self.args.loss.loss_grad1_mse_scale,
748
+ f0_max=self.args.model.f0_max,
749
+ f0_min=self.args.model.f0_min,
750
+ confidence=self.args.model.confidence,
751
+ )
752
+ model.to(self.device).to(self.dtype)
753
+ model.load_state_dict(ckpt["model"])
754
+ model.eval()
755
+ self.model = model
756
+ self.wav2mel = Wav2Mel(self.args, dtype=self.dtype, device=self.device)
757
+
758
+ @torch.no_grad()
759
+ def __call__(self, audio, sr, threshold=0.05):
760
+ self.model.threshold = threshold
761
+ audio = audio[None, :]
762
+ mel = self.wav2mel(audio=audio, sample_rate=sr).to(self.dtype)
763
+ f0 = self.model(mel=mel, infer=True, return_hz_f0=True)
764
+ return f0
765
+
766
+
767
+ class Wav2Mel:
768
+ def __init__(self, args, device=None, dtype=torch.float32):
769
+ self.sample_rate = args.mel.sampling_rate
770
+ self.hop_size = args.mel.hop_size
771
+ if device is None:
772
+ device = "cuda" if torch.cuda.is_available() else "cpu"
773
+ self.device = device
774
+ self.dtype = dtype
775
+ self.stft = STFT(
776
+ args.mel.sampling_rate,
777
+ args.mel.num_mels,
778
+ args.mel.n_fft,
779
+ args.mel.win_size,
780
+ args.mel.hop_size,
781
+ args.mel.fmin,
782
+ args.mel.fmax,
783
+ )
784
+ self.resample_kernel = {}
785
+
786
+ def extract_nvstft(self, audio, keyshift=0, train=False):
787
+ mel = self.stft.get_mel(audio, keyshift=keyshift, train=train).transpose(1, 2)
788
+ return mel
789
+
790
+ def extract_mel(self, audio, sample_rate, keyshift=0, train=False):
791
+ audio = audio.to(self.dtype).to(self.device)
792
+ if sample_rate == self.sample_rate:
793
+ audio_res = audio
794
+ else:
795
+ key_str = str(sample_rate)
796
+ if key_str not in self.resample_kernel:
797
+ self.resample_kernel[key_str] = Resample(
798
+ sample_rate, self.sample_rate, lowpass_filter_width=128
799
+ )
800
+ self.resample_kernel[key_str] = (
801
+ self.resample_kernel[key_str].to(self.dtype).to(self.device)
802
+ )
803
+ audio_res = self.resample_kernel[key_str](audio)
804
+
805
+ mel = self.extract_nvstft(
806
+ audio_res, keyshift=keyshift, train=train
807
+ ) # B, n_frames, bins
808
+ n_frames = int(audio.shape[1] // self.hop_size) + 1
809
+ mel = (
810
+ torch.cat((mel, mel[:, -1:, :]), 1) if n_frames > int(mel.shape[1]) else mel
811
+ )
812
+ mel = mel[:, :n_frames, :] if n_frames < int(mel.shape[1]) else mel
813
+ return mel
814
+
815
+ def __call__(self, audio, sample_rate, keyshift=0, train=False):
816
+ return self.extract_mel(audio, sample_rate, keyshift=keyshift, train=train)
817
+
818
+
819
+ class DotDict(dict):
820
+ def __getattr__(*args):
821
+ val = dict.get(*args)
822
+ return DotDict(val) if type(val) is dict else val
823
+
824
+ __setattr__ = dict.__setitem__
825
+ __delattr__ = dict.__delitem__
826
+
827
+
828
+ class F0Predictor(object):
829
+ def compute_f0(self, wav, p_len):
830
+ pass
831
+
832
+ def compute_f0_uv(self, wav, p_len):
833
+ pass
834
+
835
+
836
+ class FCPEF0Predictor(F0Predictor):
837
+ def __init__(
838
+ self,
839
+ model_path,
840
+ hop_length=512,
841
+ f0_min=50,
842
+ f0_max=1100,
843
+ dtype=torch.float32,
844
+ device=None,
845
+ sample_rate=44100,
846
+ threshold=0.05,
847
+ ):
848
+ self.fcpe = FCPEInfer(model_path, device=device, dtype=dtype)
849
+ self.hop_length = hop_length
850
+ self.f0_min = f0_min
851
+ self.f0_max = f0_max
852
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
853
+ self.threshold = threshold
854
+ self.sample_rate = sample_rate
855
+ self.dtype = dtype
856
+ self.name = "fcpe"
857
+
858
+ def repeat_expand(
859
+ self,
860
+ content: Union[torch.Tensor, np.ndarray],
861
+ target_len: int,
862
+ mode: str = "nearest",
863
+ ):
864
+ ndim = content.ndim
865
+ content = (
866
+ content[None, None]
867
+ if ndim == 1
868
+ else content[None] if ndim == 2 else content
869
+ )
870
+ assert content.ndim == 3
871
+ is_np = isinstance(content, np.ndarray)
872
+ content = torch.from_numpy(content) if is_np else content
873
+ results = torch.nn.functional.interpolate(content, size=target_len, mode=mode)
874
+ results = results.numpy() if is_np else results
875
+ return results[0, 0] if ndim == 1 else results[0] if ndim == 2 else results
876
+
877
+ def post_process(self, x, sample_rate, f0, pad_to):
878
+ f0 = (
879
+ torch.from_numpy(f0).float().to(x.device)
880
+ if isinstance(f0, np.ndarray)
881
+ else f0
882
+ )
883
+ f0 = self.repeat_expand(f0, pad_to) if pad_to is not None else f0
884
+
885
+ vuv_vector = torch.zeros_like(f0)
886
+ vuv_vector[f0 > 0.0] = 1.0
887
+ vuv_vector[f0 <= 0.0] = 0.0
888
+
889
+ nzindex = torch.nonzero(f0).squeeze()
890
+ f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
891
+ time_org = self.hop_length / sample_rate * nzindex.cpu().numpy()
892
+ time_frame = np.arange(pad_to) * self.hop_length / sample_rate
893
+
894
+ vuv_vector = F.interpolate(vuv_vector[None, None, :], size=pad_to)[0][0]
895
+
896
+ if f0.shape[0] <= 0:
897
+ return np.zeros(pad_to), vuv_vector.cpu().numpy()
898
+ if f0.shape[0] == 1:
899
+ return np.ones(pad_to) * f0[0], vuv_vector.cpu().numpy()
900
+
901
+ f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
902
+ return f0, vuv_vector.cpu().numpy()
903
+
904
+ def compute_f0(self, wav, p_len=None):
905
+ x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
906
+ p_len = x.shape[0] // self.hop_length if p_len is None else p_len
907
+ f0 = self.fcpe(x, sr=self.sample_rate, threshold=self.threshold)[0, :, 0]
908
+ if torch.all(f0 == 0):
909
+ return f0.cpu().numpy() if p_len is None else np.zeros(p_len)
910
+ return self.post_process(x, self.sample_rate, f0, p_len)[0]
911
+
912
+ def compute_f0_uv(self, wav, p_len=None):
913
+ x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
914
+ p_len = x.shape[0] // self.hop_length if p_len is None else p_len
915
+ f0 = self.fcpe(x, sr=self.sample_rate, threshold=self.threshold)[0, :, 0]
916
+ if torch.all(f0 == 0):
917
+ return f0.cpu().numpy() if p_len is None else np.zeros(p_len), (
918
+ f0.cpu().numpy() if p_len is None else np.zeros(p_len)
919
+ )
920
+ return self.post_process(x, self.sample_rate, f0, p_len)