Spaces:
Runtime error
Runtime error
File size: 25,211 Bytes
0164e4a 947703f 0164e4a |
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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 |
import torch
from torch import nn
from torch.nn import functional as F
import modules
import attentions
from torch.nn import Conv1d, ConvTranspose1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from commons import init_weights, get_padding
import torchaudio
from einops import rearrange
import transformers
import math
from styleencoder import StyleEncoder
import commons
from alias_free_torch import *
import activations
class Wav2vec2(torch.nn.Module):
def __init__(self, layer=7, w2v='mms'):
"""we use the intermediate features of mms-300m.
More specifically, we used the output from the 7th layer of the 24-layer transformer encoder.
"""
super().__init__()
if w2v == 'mms':
self.wav2vec2 = transformers.Wav2Vec2ForPreTraining.from_pretrained("facebook/mms-300m")
else:
self.wav2vec2 = transformers.Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-xls-r-300m")
for param in self.wav2vec2.parameters():
param.requires_grad = False
param.grad = None
self.wav2vec2.eval()
self.feature_layer = layer
@torch.no_grad()
def forward(self, x):
"""
Args:
x: torch.Tensor of shape (B x t)
Returns:
y: torch.Tensor of shape(B x C x t)
"""
outputs = self.wav2vec2(x.squeeze(1), output_hidden_states=True)
y = outputs.hidden_states[self.feature_layer] # B x t x C(1024)
y = y.permute((0, 2, 1)) # B x t x C -> B x C x t
return y
class ResidualCouplingBlock_Transformer(nn.Module):
def __init__(self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers=3,
n_flows=4,
gin_channels=0):
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.n_flows = n_flows
self.gin_channels = gin_channels
self.cond_block = torch.nn.Sequential(torch.nn.Linear(gin_channels, 4 * hidden_channels),
nn.SiLU(), torch.nn.Linear(4 * hidden_channels, hidden_channels))
self.flows = nn.ModuleList()
for i in range(n_flows):
self.flows.append(modules.ResidualCouplingLayer_Transformer_simple(channels, hidden_channels, kernel_size, dilation_rate, n_layers, mean_only=True))
self.flows.append(modules.Flip())
def forward(self, x, x_mask, g=None, reverse=False):
g = self.cond_block(g.squeeze(2))
if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x = flow(x, x_mask, g=g, reverse=reverse)
return x
class PosteriorAudioEncoder(nn.Module):
def __init__(self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
self.down_pre = nn.Conv1d(1, 16, 7, 1, padding=3)
self.resblocks = nn.ModuleList()
downsample_rates = [8,5,4,2]
downsample_kernel_sizes = [17, 10, 8, 4]
ch = [16, 32, 64, 128, 192]
resblock = AMPBlock1
resblock_kernel_sizes = [3,7,11]
resblock_dilation_sizes = [[1,3,5], [1,3,5], [1,3,5]]
self.num_kernels = 3
self.downs = nn.ModuleList()
for i, (u, k) in enumerate(zip(downsample_rates, downsample_kernel_sizes)):
self.downs.append(weight_norm(
Conv1d(ch[i], ch[i+1], k, u, padding=(k-1)//2)))
for i in range(4):
for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
self.resblocks.append(resblock(ch[i+1], k, d, activation="snakebeta"))
activation_post = activations.SnakeBeta(ch[i+1], alpha_logscale=True)
self.activation_post = Activation1d(activation=activation_post)
self.conv_post = Conv1d(ch[i+1], hidden_channels, 7, 1, padding=3)
self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
self.proj = nn.Conv1d(hidden_channels*2, out_channels * 2, 1)
def forward(self, x, x_audio, x_mask, g=None):
x_audio = self.down_pre(x_audio)
for i in range(4):
x_audio = self.downs[i](x_audio)
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i*self.num_kernels+j](x_audio)
else:
xs += self.resblocks[i*self.num_kernels+j](x_audio)
x_audio = xs / self.num_kernels
x_audio = self.activation_post(x_audio)
x_audio = self.conv_post(x_audio)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
x_audio = x_audio * x_mask
x = torch.cat([x, x_audio], dim=1)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m, logs
class PosteriorSFEncoder(nn.Module):
def __init__(self,
src_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0):
super().__init__()
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.pre_source = nn.Conv1d(src_channels, hidden_channels, 1)
self.pre_filter = nn.Conv1d(1, hidden_channels, kernel_size=9, stride=4, padding=4)
self.source_enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers//2, gin_channels=gin_channels)
self.filter_enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers//2, gin_channels=gin_channels)
self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers//2, gin_channels=gin_channels)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, x_src, x_ftr, x_mask, g=None):
x_src = self.pre_source(x_src) * x_mask
x_ftr = self.pre_filter(x_ftr) * x_mask
x_src = self.source_enc(x_src, x_mask, g=g)
x_ftr = self.filter_enc(x_ftr, x_mask, g=g)
x = self.enc(x_src+x_ftr, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m, logs
class MelDecoder(nn.Module):
def __init__(self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
mel_size=20,
gin_channels=0):
super().__init__()
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.conv_pre = Conv1d(hidden_channels, hidden_channels, 3, 1, padding=1)
self.encoder = attentions.Encoder(
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout)
self.proj= nn.Conv1d(hidden_channels, mel_size, 1, bias=False)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, hidden_channels, 1)
def forward(self, x, x_mask, g=None):
x = self.conv_pre(x*x_mask)
if g is not None:
x = x + self.cond(g)
x = self.encoder(x * x_mask, x_mask)
x = self.proj(x) * x_mask
return x
class SourceNetwork(nn.Module):
def __init__(self, upsample_initial_channel=256):
super().__init__()
resblock_kernel_sizes = [3,5,7]
upsample_rates = [2,2]
initial_channel = 192
upsample_initial_channel = upsample_initial_channel
upsample_kernel_sizes = [4,4]
resblock_dilation_sizes = [[1,3,5], [1,3,5], [1,3,5]]
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.conv_pre = weight_norm(Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3))
resblock = AMPBlock1
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
self.ups.append(weight_norm(
ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
k, u, padding=(k-u)//2)))
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel//(2**(i+1))
for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
self.resblocks.append(resblock(ch, k, d, activation="snakebeta"))
activation_post = activations.SnakeBeta(ch, alpha_logscale=True)
self.activation_post = Activation1d(activation=activation_post)
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
self.cond = Conv1d(256, upsample_initial_channel, 1)
self.ups.apply(init_weights)
def forward(self, x, g):
x = self.conv_pre(x) + self.cond(g)
for i in range(self.num_upsamples):
x = self.ups[i](x)
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i*self.num_kernels+j](x)
else:
xs += self.resblocks[i*self.num_kernels+j](x)
x = xs / self.num_kernels
x = self.activation_post(x)
## Predictor
x_ = self.conv_post(x)
return x, x_
def remove_weight_norm(self):
print('Removing weight norm...')
for l in self.ups:
remove_weight_norm(l)
for l in self.resblocks:
l.remove_weight_norm()
class DBlock(nn.Module):
def __init__(self, input_size, hidden_size, factor):
super().__init__()
self.factor = factor
self.residual_dense = weight_norm(Conv1d(input_size, hidden_size, 1))
self.conv = nn.ModuleList([
weight_norm(Conv1d(input_size, hidden_size, 3, dilation=1, padding=1)),
weight_norm(Conv1d(hidden_size, hidden_size, 3, dilation=2, padding=2)),
weight_norm(Conv1d(hidden_size, hidden_size, 3, dilation=4, padding=4)),
])
self.conv.apply(init_weights)
def forward(self, x):
size = x.shape[-1] // self.factor
residual = self.residual_dense(x)
residual = F.interpolate(residual, size=size)
x = F.interpolate(x, size=size)
for layer in self.conv:
x = F.leaky_relu(x, modules.LRELU_SLOPE)
x = layer(x)
return x + residual
def remove_weight_norm(self):
for l in self.conv:
remove_weight_norm(l)
class AMPBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), activation=None):
super(AMPBlock1, self).__init__()
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2])))
])
self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1)))
])
self.convs2.apply(init_weights)
self.num_layers = len(self.convs1) + len(self.convs2) # total number of conv layers
self.activations = nn.ModuleList([
Activation1d(
activation=activations.SnakeBeta(channels, alpha_logscale=True))
for _ in range(self.num_layers)
])
def forward(self, x):
acts1, acts2 = self.activations[::2], self.activations[1::2]
for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2):
xt = a1(x)
xt = c1(xt)
xt = a2(xt)
xt = c2(xt)
x = xt + x
return x
def remove_weight_norm(self):
for l in self.convs1:
remove_weight_norm(l)
for l in self.convs2:
remove_weight_norm(l)
class Generator(torch.nn.Module):
def __init__(self, initial_channel, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=256):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.conv_pre = weight_norm(Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3))
resblock = AMPBlock1
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
self.ups.append(weight_norm(
ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
k, u, padding=(k-u)//2)))
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel//(2**(i+1))
for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
self.resblocks.append(resblock(ch, k, d, activation="snakebeta"))
activation_post = activations.SnakeBeta(ch, alpha_logscale=True)
self.activation_post = Activation1d(activation=activation_post)
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
self.ups.apply(init_weights)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
self.downs = DBlock(upsample_initial_channel//8, upsample_initial_channel, 4)
self.proj = Conv1d(upsample_initial_channel//8, upsample_initial_channel//2, 7, 1, padding=3)
def forward(self, x, pitch, g=None):
x = self.conv_pre(x) + self.downs(pitch) + self.cond(g)
for i in range(self.num_upsamples):
x = self.ups[i](x)
if i == 0:
pitch = self.proj(pitch)
x = x + pitch
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i*self.num_kernels+j](x)
else:
xs += self.resblocks[i*self.num_kernels+j](x)
x = xs / self.num_kernels
x = self.activation_post(x)
x = self.conv_post(x)
x = torch.tanh(x)
return x
def remove_weight_norm(self):
print('Removing weight norm...')
for l in self.ups:
remove_weight_norm(l)
for l in self.resblocks:
l.remove_weight_norm()
for l in self.downs:
l.remove_weight_norm()
remove_weight_norm(self.conv_pre)
class DiscriminatorP(torch.nn.Module):
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
super(DiscriminatorP, self).__init__()
self.period = period
self.use_spectral_norm = use_spectral_norm
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
self.convs = nn.ModuleList([
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
])
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
def forward(self, x):
fmap = []
# 1d to 2d
b, c, t = x.shape
if t % self.period != 0: # pad first
n_pad = self.period - (t % self.period)
x = F.pad(x, (0, n_pad), "reflect")
t = t + n_pad
x = x.view(b, c, t // self.period, self.period)
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, modules.LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap
class DiscriminatorR(torch.nn.Module):
def __init__(self, resolution, use_spectral_norm=False):
super(DiscriminatorR, self).__init__()
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
n_fft, hop_length, win_length = resolution
self.spec_transform = torchaudio.transforms.Spectrogram(
n_fft=n_fft, hop_length=hop_length, win_length=win_length, window_fn=torch.hann_window,
normalized=True, center=False, pad_mode=None, power=None)
self.convs = nn.ModuleList([
norm_f(nn.Conv2d(2, 32, (3, 9), padding=(1, 4))),
norm_f(nn.Conv2d(32, 32, (3, 9), stride=(1, 2), padding=(1, 4))),
norm_f(nn.Conv2d(32, 32, (3, 9), stride=(1, 2), dilation=(2,1), padding=(2, 4))),
norm_f(nn.Conv2d(32, 32, (3, 9), stride=(1, 2), dilation=(4,1), padding=(4, 4))),
norm_f(nn.Conv2d(32, 32, (3, 3), padding=(1, 1))),
])
self.conv_post = norm_f(nn.Conv2d(32, 1, (3, 3), padding=(1, 1)))
def forward(self, y):
fmap = []
x = self.spec_transform(y) # [B, 2, Freq, Frames, 2]
x = torch.cat([x.real, x.imag], dim=1)
x = rearrange(x, 'b c w t -> b c t w')
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, modules.LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap
class MultiPeriodDiscriminator(torch.nn.Module):
def __init__(self, use_spectral_norm=False):
super(MultiPeriodDiscriminator, self).__init__()
periods = [2,3,5,7,11]
resolutions = [[2048, 512, 2048], [1024, 256, 1024], [512, 128, 512], [256, 64, 256], [128, 32, 128]]
discs = [DiscriminatorR(resolutions[i], use_spectral_norm=use_spectral_norm) for i in range(len(resolutions))]
discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
self.discriminators = nn.ModuleList(discs)
def forward(self, y, y_hat):
y_d_rs = []
y_d_gs = []
fmap_rs = []
fmap_gs = []
for i, d in enumerate(self.discriminators):
y_d_r, fmap_r = d(y)
y_d_g, fmap_g = d(y_hat)
y_d_rs.append(y_d_r)
y_d_gs.append(y_d_g)
fmap_rs.append(fmap_r)
fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
class SynthesizerTrn(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=256,
prosody_size=20,
uncond_ratio=0.,
cfg=False,
**kwargs):
super().__init__()
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.mel_size = prosody_size
self.enc_p_l = PosteriorSFEncoder(1024, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
self.flow_l = ResidualCouplingBlock_Transformer(inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)
self.enc_p = PosteriorSFEncoder(1024, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
self.enc_q = PosteriorAudioEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
self.flow = ResidualCouplingBlock_Transformer(inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)
self.mel_decoder = MelDecoder(inter_channels,
filter_channels,
n_heads=2,
n_layers=2,
kernel_size=5,
p_dropout=0.1,
mel_size=self.mel_size,
gin_channels=gin_channels)
self.dec = Generator(inter_channels, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
self.sn = SourceNetwork(upsample_initial_channel//2)
self.emb_g = StyleEncoder(in_dim=80, hidden_dim=256, out_dim=gin_channels)
if cfg:
self.emb = torch.nn.Embedding(1, 256)
torch.nn.init.normal_(self.emb.weight, 0.0, 256 ** -0.5)
self.null = torch.LongTensor([0])
self.uncond_ratio = uncond_ratio
self.cfg = cfg
@torch.no_grad()
def infer(self, x_mel, w2v, length, f0):
x_mask = torch.unsqueeze(commons.sequence_mask(length, x_mel.size(2)), 1).to(x_mel.dtype)
# Speaker embedding from mel (Style Encoder)
g = self.emb_g(x_mel, x_mask).unsqueeze(-1)
z, _, _ = self.enc_p_l(w2v, f0, x_mask, g=g)
z = self.flow_l(z, x_mask, g=g, reverse=True)
z = self.flow(z, x_mask, g=g, reverse=True)
e, e_ = self.sn(z, g)
o = self.dec(z, e, g=g)
return o, e_
@torch.no_grad()
def voice_conversion(self, src, src_length, trg_mel, trg_length, f0, noise_scale = 0.333, uncond=False):
trg_mask = torch.unsqueeze(commons.sequence_mask(trg_length, trg_mel.size(2)), 1).to(trg_mel.dtype)
g = self.emb_g(trg_mel, trg_mask).unsqueeze(-1)
y_mask = torch.unsqueeze(commons.sequence_mask(src_length, src.size(2)), 1).to(trg_mel.dtype)
z, m_p, logs_p = self.enc_p_l(src, f0, y_mask, g=g)
z = (m_p + torch.randn_like(m_p) * torch.exp(logs_p)*noise_scale) * y_mask
z = self.flow_l(z, y_mask, g=g, reverse=True)
z = self.flow(z, y_mask, g=g, reverse=True)
if uncond:
null_emb = self.emb(self.null) * math.sqrt(256)
g = null_emb.unsqueeze(-1)
e, _ = self.sn(z, g)
o = self.dec(z, e, g=g)
return o
@torch.no_grad()
def voice_conversion_noise_control(self, src, src_length, trg_mel, trg_length, f0, noise_scale = 0.333, uncond=False, denoise_ratio = 0):
trg_mask = torch.unsqueeze(commons.sequence_mask(trg_length, trg_mel.size(2)), 1).to(trg_mel.dtype)
g = self.emb_g(trg_mel, trg_mask).unsqueeze(-1)
g_org, g_denoise = g[:1, :, :], g[1:, :, :]
g_interpolation = (1-denoise_ratio)*g_org + denoise_ratio*g_denoise
y_mask = torch.unsqueeze(commons.sequence_mask(src_length, src.size(2)), 1).to(trg_mel.dtype)
z, m_p, logs_p = self.enc_p_l(src, f0, y_mask, g=g_interpolation)
z = (m_p + torch.randn_like(m_p) * torch.exp(logs_p)*noise_scale) * y_mask
z = self.flow_l(z, y_mask, g=g_interpolation, reverse=True)
z = self.flow(z, y_mask, g=g_interpolation, reverse=True)
if uncond:
null_emb = self.emb(self.null) * math.sqrt(256)
g = null_emb.unsqueeze(-1)
e, _ = self.sn(z, g_interpolation)
o = self.dec(z, e, g=g_interpolation)
return o
@torch.no_grad()
def f0_extraction(self, x_linear, x_mel, length, x_audio, noise_scale = 0.333):
x_mask = torch.unsqueeze(commons.sequence_mask(length, x_mel.size(2)), 1).to(x_mel.dtype)
# Speaker embedding from mel (Style Encoder)
g = self.emb_g(x_mel, x_mask).unsqueeze(-1)
# posterior encoder from linear spec.
_, m_q, logs_q= self.enc_q(x_linear, x_audio, x_mask, g=g)
z = (m_q + torch.randn_like(m_q) * torch.exp(logs_q)*noise_scale)
# Source Networks
_, e_ = self.sn(z, g)
return e_
|