Spaces:
Runtime error
Runtime error
junhyouk lee
commited on
Commit
•
b8b70ac
1
Parent(s):
b8336df
hfdemo
Browse files- README.md +4 -4
- analysis.py +141 -0
- app.py +141 -0
- attentions.py +472 -0
- commons.py +181 -0
- configs/config_en.yaml +68 -0
- logs/pits_vctk_AD_3000.pth +3 -0
- models.py +1383 -0
- modules.py +425 -0
- pqmf.py +136 -0
- text/__init__.py +68 -0
- text/cleaners.py +89 -0
- text/numbers.py +71 -0
- text/symbols.py +38 -0
- transforms.py +199 -0
- utils.py +309 -0
- yin.py +166 -0
README.md
CHANGED
@@ -1,13 +1,13 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
emoji: 🌖
|
4 |
colorFrom: purple
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 3.20.
|
8 |
app_file: app.py
|
9 |
-
pinned:
|
10 |
license: mit
|
11 |
---
|
12 |
|
13 |
-
|
|
|
1 |
---
|
2 |
+
title: PITS
|
3 |
emoji: 🌖
|
4 |
colorFrom: purple
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.20.1
|
8 |
app_file: app.py
|
9 |
+
pinned: true
|
10 |
license: mit
|
11 |
---
|
12 |
|
13 |
+
Official Demo for PITS: Variational Pitch Inference without Fundamental Frequency for End-to-End Pitch-controllable TTS
|
analysis.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/dhchoi99/NANSY
|
2 |
+
# We have modified the implementation of dhchoi99 to be fully differentiable.
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
from yin import *
|
6 |
+
|
7 |
+
|
8 |
+
class Pitch(torch.nn.Module):
|
9 |
+
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
sr=22050,
|
13 |
+
w_step=256,
|
14 |
+
W=2048,
|
15 |
+
tau_max=2048,
|
16 |
+
midi_start=5,
|
17 |
+
midi_end=85,
|
18 |
+
octave_range=12):
|
19 |
+
super(Pitch, self).__init__()
|
20 |
+
self.sr = sr
|
21 |
+
self.w_step = w_step
|
22 |
+
self.W = W
|
23 |
+
self.tau_max = tau_max
|
24 |
+
self.unfold = torch.nn.Unfold((1, self.W),
|
25 |
+
1,
|
26 |
+
0,
|
27 |
+
stride=(1, self.w_step))
|
28 |
+
midis = list(range(midi_start, midi_end))
|
29 |
+
self.len_midis = len(midis)
|
30 |
+
c_ms = torch.tensor([self.midi_to_lag(m, octave_range) for m in midis])
|
31 |
+
self.register_buffer('c_ms', c_ms)
|
32 |
+
self.register_buffer('c_ms_ceil', torch.ceil(self.c_ms).long())
|
33 |
+
self.register_buffer('c_ms_floor', torch.floor(self.c_ms).long())
|
34 |
+
|
35 |
+
def midi_to_lag(self, m: int, octave_range: float = 12):
|
36 |
+
"""converts midi-to-lag, eq. (4)
|
37 |
+
|
38 |
+
Args:
|
39 |
+
m: midi
|
40 |
+
sr: sample_rate
|
41 |
+
octave_range:
|
42 |
+
|
43 |
+
Returns:
|
44 |
+
lag: time lag(tau, c(m)) calculated from midi, eq. (4)
|
45 |
+
|
46 |
+
"""
|
47 |
+
f = 440 * math.pow(2, (m - 69) / octave_range)
|
48 |
+
lag = self.sr / f
|
49 |
+
return lag
|
50 |
+
|
51 |
+
def yingram_from_cmndf(self, cmndfs: torch.Tensor) -> torch.Tensor:
|
52 |
+
""" yingram calculator from cMNDFs(cumulative Mean Normalized Difference Functions)
|
53 |
+
|
54 |
+
Args:
|
55 |
+
cmndfs: torch.Tensor
|
56 |
+
calculated cumulative mean normalized difference function
|
57 |
+
for details, see models/yin.py or eq. (1) and (2)
|
58 |
+
ms: list of midi(int)
|
59 |
+
sr: sampling rate
|
60 |
+
|
61 |
+
Returns:
|
62 |
+
y:
|
63 |
+
calculated batch yingram
|
64 |
+
|
65 |
+
|
66 |
+
"""
|
67 |
+
#c_ms = np.asarray([Pitch.midi_to_lag(m, sr) for m in ms])
|
68 |
+
#c_ms = torch.from_numpy(c_ms).to(cmndfs.device)
|
69 |
+
|
70 |
+
y = (cmndfs[:, self.c_ms_ceil] -
|
71 |
+
cmndfs[:, self.c_ms_floor]) / (self.c_ms_ceil - self.c_ms_floor).unsqueeze(0) * (
|
72 |
+
self.c_ms - self.c_ms_floor).unsqueeze(0) + cmndfs[:, self.c_ms_floor]
|
73 |
+
return y
|
74 |
+
|
75 |
+
def yingram(self, x: torch.Tensor):
|
76 |
+
"""calculates yingram from raw audio (multi segment)
|
77 |
+
|
78 |
+
Args:
|
79 |
+
x: raw audio, torch.Tensor of shape (t)
|
80 |
+
W: yingram Window Size
|
81 |
+
tau_max:
|
82 |
+
sr: sampling rate
|
83 |
+
w_step: yingram bin step size
|
84 |
+
|
85 |
+
Returns:
|
86 |
+
yingram: yingram. torch.Tensor of shape (80 x t')
|
87 |
+
|
88 |
+
"""
|
89 |
+
# x.shape: t -> B,T, B,T = x.shape
|
90 |
+
B, T = x.shape
|
91 |
+
w_len = self.W
|
92 |
+
|
93 |
+
|
94 |
+
frames = self.unfold(x.view(B, 1, 1, T))
|
95 |
+
frames = frames.permute(0, 2,
|
96 |
+
1).contiguous().view(-1,
|
97 |
+
self.W) #[B* frames, W]
|
98 |
+
# If not using gpu, or torch not compatible, implemented numpy batch function is still fine
|
99 |
+
dfs = differenceFunctionTorch(frames, frames.shape[-1], self.tau_max)
|
100 |
+
cmndfs = cumulativeMeanNormalizedDifferenceFunctionTorch(
|
101 |
+
dfs, self.tau_max)
|
102 |
+
yingram = self.yingram_from_cmndf(cmndfs) #[B*frames,F]
|
103 |
+
yingram = yingram.view(B, -1, self.len_midis).permute(0, 2,
|
104 |
+
1) # [B,F,T]
|
105 |
+
return yingram
|
106 |
+
|
107 |
+
def crop_scope(self, x, yin_start,
|
108 |
+
scope_shift): # x: tensor [B,C,T] #scope_shift: tensor [B]
|
109 |
+
return torch.stack([
|
110 |
+
x[i, yin_start + scope_shift[i]:yin_start + self.yin_scope +
|
111 |
+
scope_shift[i], :] for i in range(x.shape[0])
|
112 |
+
],
|
113 |
+
dim=0)
|
114 |
+
|
115 |
+
|
116 |
+
if __name__ == '__main__':
|
117 |
+
import torch
|
118 |
+
import librosa as rosa
|
119 |
+
import matplotlib.pyplot as plt
|
120 |
+
wav = torch.tensor(rosa.load('LJ001-0002.wav', sr=22050,
|
121 |
+
mono=True)[0]).unsqueeze(0)
|
122 |
+
# wav = torch.randn(1,40965)
|
123 |
+
|
124 |
+
wav = torch.nn.functional.pad(wav, (0, (-wav.shape[1]) % 256))
|
125 |
+
# wav = wav[#:,:8096]
|
126 |
+
print(wav.shape)
|
127 |
+
pitch = Pitch()
|
128 |
+
|
129 |
+
with torch.no_grad():
|
130 |
+
ps = pitch.yingram(torch.nn.functional.pad(wav, (1024, 1024)))
|
131 |
+
ps = torch.nn.functional.pad(ps, (0, 0, 8, 8), mode='replicate')
|
132 |
+
print(ps.shape)
|
133 |
+
spec = torch.stft(wav, 1024, 256, return_complex=False)
|
134 |
+
print(spec.shape)
|
135 |
+
plt.subplot(2, 1, 1)
|
136 |
+
plt.pcolor(ps[0].numpy(), cmap='magma')
|
137 |
+
plt.colorbar()
|
138 |
+
plt.subplot(2, 1, 2)
|
139 |
+
plt.pcolor(ps[0][15:65, :].numpy(), cmap='magma')
|
140 |
+
plt.colorbar()
|
141 |
+
plt.show()
|
app.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import argparse
|
3 |
+
import torch
|
4 |
+
import commons
|
5 |
+
import utils
|
6 |
+
from models import (
|
7 |
+
SynthesizerTrn, )
|
8 |
+
|
9 |
+
from text.symbols import symbol_len, lang_to_dict
|
10 |
+
|
11 |
+
# we use Kyubyong/g2p for demo instead of our internal g2p
|
12 |
+
# https://github.com/Kyubyong/g2p
|
13 |
+
from g2p_en import G2p
|
14 |
+
import re
|
15 |
+
|
16 |
+
_symbol_to_id = lang_to_dict("en_US")
|
17 |
+
|
18 |
+
class GradioApp:
|
19 |
+
|
20 |
+
def __init__(self, args):
|
21 |
+
self.hps = utils.get_hparams_from_file(args.config)
|
22 |
+
self.device = "cpu"
|
23 |
+
self.net_g = SynthesizerTrn(symbol_len(self.hps.data.languages),
|
24 |
+
self.hps.data.filter_length // 2 + 1,
|
25 |
+
self.hps.train.segment_size //
|
26 |
+
self.hps.data.hop_length,
|
27 |
+
midi_start=-5,
|
28 |
+
midi_end=75,
|
29 |
+
octave_range=24,
|
30 |
+
n_speakers=len(self.hps.data.speakers),
|
31 |
+
**self.hps.model).to(self.device)
|
32 |
+
_ = self.net_g.eval()
|
33 |
+
_ = utils.load_checkpoint(args.checkpoint_path, model_g=self.net_g)
|
34 |
+
self.g2p = G2p()
|
35 |
+
self.interface = self._gradio_interface()
|
36 |
+
|
37 |
+
def get_phoneme(self, text):
|
38 |
+
phones = [re.sub("[0-9]", "", p) for p in self.g2p(text)]
|
39 |
+
tone = [0 for p in phones]
|
40 |
+
if self.hps.data.add_blank:
|
41 |
+
text_norm = [_symbol_to_id[symbol] for symbol in phones]
|
42 |
+
text_norm = commons.intersperse(text_norm, 0)
|
43 |
+
tone = commons.intersperse(tone, 0)
|
44 |
+
else:
|
45 |
+
text_norm = phones
|
46 |
+
text_norm = torch.LongTensor(text_norm)
|
47 |
+
tone = torch.LongTensor(tone)
|
48 |
+
return text_norm, tone, phones
|
49 |
+
|
50 |
+
@torch.no_grad()
|
51 |
+
def inference(self, text, speaker_id_val, seed, scope_shift, duration):
|
52 |
+
torch.manual_seed(seed)
|
53 |
+
text_norm, tone, phones = self.get_phoneme(text)
|
54 |
+
x_tst = text_norm.to(self.device).unsqueeze(0)
|
55 |
+
t_tst = tone.to(self.device).unsqueeze(0)
|
56 |
+
x_tst_lengths = torch.LongTensor([text_norm.size(0)]).to(self.device)
|
57 |
+
speaker_id = torch.LongTensor([speaker_id_val]).to(self.device)
|
58 |
+
decoder_inputs,*_ = self.net_g.infer_pre_decoder(
|
59 |
+
x_tst,
|
60 |
+
t_tst,
|
61 |
+
x_tst_lengths,
|
62 |
+
sid=speaker_id,
|
63 |
+
noise_scale=0.667,
|
64 |
+
noise_scale_w=0.8,
|
65 |
+
length_scale=duration,
|
66 |
+
scope_shift=scope_shift)
|
67 |
+
audio = self.net_g.infer_decode_chunk(
|
68 |
+
decoder_inputs, sid=speaker_id)[0, 0].data.cpu().float().numpy()
|
69 |
+
del decoder_inputs,
|
70 |
+
return phones, (self.hps.data.sampling_rate, audio)
|
71 |
+
|
72 |
+
|
73 |
+
def _gradio_interface(self):
|
74 |
+
title = "PITS Demo"
|
75 |
+
inputs = [
|
76 |
+
gr.Textbox(label="Text (150 words limitation)",
|
77 |
+
value="This is demo page.",
|
78 |
+
elem_id="tts-input"),
|
79 |
+
gr.Dropdown(list(self.hps.data.speakers),
|
80 |
+
value="p225",
|
81 |
+
label="Speaker Identity",
|
82 |
+
type="index"),
|
83 |
+
gr.Slider(0, 65536, step=1, label="random seed"),
|
84 |
+
gr.Slider(-15, 15, value=0, step=1, label="scope-shift"),
|
85 |
+
gr.Slider(0.5, 2., value=1., step=0.1,
|
86 |
+
label="duration multiplier"),
|
87 |
+
]
|
88 |
+
outputs = [
|
89 |
+
gr.Textbox(label="Phonemes"),
|
90 |
+
gr.Audio(type="numpy", label="Output audio")
|
91 |
+
]
|
92 |
+
description = "Welcome to the Gradio demo for PITS: Variational Pitch Inference without Fundamental Frequency for End-to-End Pitch-controllable TTS.\n In this demo, we utilize an open-source G2P library (g2p_en) with stress removing, instead of our internal G2P.\n You can fix the latent z by controlling random seed.\n You can shift the pitch scope, but please note that this is opposite to pitch-shift. In addition, it is cropped from fixed z so please check pitch-controllability by comparing with normal synthesis.\n Thank you for trying out our PITS demo!"
|
93 |
+
article = "Github:https://github.com/anonymous-pits/pits \n Our current preprint contains several errors. Please wait for next update."
|
94 |
+
examples = [["This is a demo page of the PITS."],["I love hugging face."]]
|
95 |
+
return gr.Interface(
|
96 |
+
fn=self.inference,
|
97 |
+
inputs=inputs,
|
98 |
+
outputs=outputs,
|
99 |
+
title=title,
|
100 |
+
description=description,
|
101 |
+
article=article,
|
102 |
+
examples=examples,
|
103 |
+
)
|
104 |
+
|
105 |
+
def launch(self):
|
106 |
+
return self.interface.launch(share=True)
|
107 |
+
|
108 |
+
|
109 |
+
def parsearg():
|
110 |
+
parser = argparse.ArgumentParser()
|
111 |
+
parser.add_argument('-c',
|
112 |
+
'--config',
|
113 |
+
type=str,
|
114 |
+
default="./configs/config_en.yaml",
|
115 |
+
help='Path to configuration file')
|
116 |
+
parser.add_argument('-m',
|
117 |
+
'--model',
|
118 |
+
type=str,
|
119 |
+
default='PITS',
|
120 |
+
help='Model name')
|
121 |
+
parser.add_argument('-r',
|
122 |
+
'--checkpoint_path',
|
123 |
+
type=str,
|
124 |
+
default='./logs/pits_vctk_AD_3000.pth',
|
125 |
+
help='Path to checkpoint for resume')
|
126 |
+
parser.add_argument('-f',
|
127 |
+
'--force_resume',
|
128 |
+
type=str,
|
129 |
+
help='Path to checkpoint for force resume')
|
130 |
+
parser.add_argument('-d',
|
131 |
+
'--dir',
|
132 |
+
type=str,
|
133 |
+
default='/DATA/audio/pits_samples',
|
134 |
+
help='root dir')
|
135 |
+
args = parser.parse_args()
|
136 |
+
return args
|
137 |
+
|
138 |
+
if __name__ == "__main__":
|
139 |
+
args = parsearg()
|
140 |
+
app = GradioApp(args)
|
141 |
+
app.launch()
|
attentions.py
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as F
|
6 |
+
|
7 |
+
import commons
|
8 |
+
from modules import LayerNorm
|
9 |
+
|
10 |
+
|
11 |
+
class Encoder(nn.Module):
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
hidden_channels,
|
15 |
+
filter_channels,
|
16 |
+
n_heads,
|
17 |
+
n_layers,
|
18 |
+
kernel_size=1,
|
19 |
+
p_dropout=0.,
|
20 |
+
window_size=4,
|
21 |
+
**kwargs
|
22 |
+
):
|
23 |
+
super().__init__()
|
24 |
+
self.hidden_channels = hidden_channels
|
25 |
+
self.filter_channels = filter_channels
|
26 |
+
self.n_heads = n_heads
|
27 |
+
self.n_layers = n_layers
|
28 |
+
self.kernel_size = kernel_size
|
29 |
+
self.p_dropout = p_dropout
|
30 |
+
self.window_size = window_size
|
31 |
+
|
32 |
+
self.drop = nn.Dropout(p_dropout)
|
33 |
+
self.attn_layers = nn.ModuleList()
|
34 |
+
self.norm_layers_1 = nn.ModuleList()
|
35 |
+
self.ffn_layers = nn.ModuleList()
|
36 |
+
self.norm_layers_2 = nn.ModuleList()
|
37 |
+
for i in range(self.n_layers):
|
38 |
+
self.attn_layers.append(
|
39 |
+
MultiHeadAttention(
|
40 |
+
hidden_channels,
|
41 |
+
hidden_channels,
|
42 |
+
n_heads,
|
43 |
+
p_dropout=p_dropout,
|
44 |
+
window_size=window_size
|
45 |
+
)
|
46 |
+
)
|
47 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
48 |
+
self.ffn_layers.append(
|
49 |
+
FFN(
|
50 |
+
hidden_channels,
|
51 |
+
hidden_channels,
|
52 |
+
filter_channels,
|
53 |
+
kernel_size,
|
54 |
+
p_dropout=p_dropout
|
55 |
+
)
|
56 |
+
)
|
57 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
58 |
+
|
59 |
+
def forward(self, x, x_mask):
|
60 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
61 |
+
x = x * x_mask
|
62 |
+
for i in range(self.n_layers):
|
63 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
64 |
+
y = self.drop(y)
|
65 |
+
x = self.norm_layers_1[i](x + y)
|
66 |
+
|
67 |
+
y = self.ffn_layers[i](x, x_mask)
|
68 |
+
y = self.drop(y)
|
69 |
+
x = self.norm_layers_2[i](x + y)
|
70 |
+
x = x * x_mask
|
71 |
+
return x
|
72 |
+
|
73 |
+
|
74 |
+
class Decoder(nn.Module):
|
75 |
+
def __init__(
|
76 |
+
self,
|
77 |
+
hidden_channels,
|
78 |
+
filter_channels,
|
79 |
+
n_heads,
|
80 |
+
n_layers,
|
81 |
+
kernel_size=1,
|
82 |
+
p_dropout=0.,
|
83 |
+
proximal_bias=False,
|
84 |
+
proximal_init=True,
|
85 |
+
**kwargs
|
86 |
+
):
|
87 |
+
super().__init__()
|
88 |
+
self.hidden_channels = hidden_channels
|
89 |
+
self.filter_channels = filter_channels
|
90 |
+
self.n_heads = n_heads
|
91 |
+
self.n_layers = n_layers
|
92 |
+
self.kernel_size = kernel_size
|
93 |
+
self.p_dropout = p_dropout
|
94 |
+
self.proximal_bias = proximal_bias
|
95 |
+
self.proximal_init = proximal_init
|
96 |
+
|
97 |
+
self.drop = nn.Dropout(p_dropout)
|
98 |
+
self.self_attn_layers = nn.ModuleList()
|
99 |
+
self.norm_layers_0 = nn.ModuleList()
|
100 |
+
self.encdec_attn_layers = nn.ModuleList()
|
101 |
+
self.norm_layers_1 = nn.ModuleList()
|
102 |
+
self.ffn_layers = nn.ModuleList()
|
103 |
+
self.norm_layers_2 = nn.ModuleList()
|
104 |
+
for i in range(self.n_layers):
|
105 |
+
self.self_attn_layers.append(
|
106 |
+
MultiHeadAttention(
|
107 |
+
hidden_channels,
|
108 |
+
hidden_channels,
|
109 |
+
n_heads,
|
110 |
+
p_dropout=p_dropout,
|
111 |
+
proximal_bias=proximal_bias,
|
112 |
+
proximal_init=proximal_init
|
113 |
+
)
|
114 |
+
)
|
115 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
116 |
+
self.encdec_attn_layers.append(
|
117 |
+
MultiHeadAttention(
|
118 |
+
hidden_channels,
|
119 |
+
hidden_channels,
|
120 |
+
n_heads,
|
121 |
+
p_dropout=p_dropout
|
122 |
+
)
|
123 |
+
)
|
124 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
125 |
+
self.ffn_layers.append(
|
126 |
+
FFN(
|
127 |
+
hidden_channels,
|
128 |
+
hidden_channels,
|
129 |
+
filter_channels,
|
130 |
+
kernel_size,
|
131 |
+
p_dropout=p_dropout,
|
132 |
+
causal=True
|
133 |
+
)
|
134 |
+
)
|
135 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
136 |
+
|
137 |
+
def forward(self, x, x_mask, h, h_mask):
|
138 |
+
"""
|
139 |
+
x: decoder input
|
140 |
+
h: encoder output
|
141 |
+
"""
|
142 |
+
self_attn_mask = commons.subsequent_mask(
|
143 |
+
x_mask.size(2)
|
144 |
+
).to(device=x.device, dtype=x.dtype)
|
145 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
146 |
+
x = x * x_mask
|
147 |
+
for i in range(self.n_layers):
|
148 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
149 |
+
y = self.drop(y)
|
150 |
+
x = self.norm_layers_0[i](x + y)
|
151 |
+
|
152 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
153 |
+
y = self.drop(y)
|
154 |
+
x = self.norm_layers_1[i](x + y)
|
155 |
+
|
156 |
+
y = self.ffn_layers[i](x, x_mask)
|
157 |
+
y = self.drop(y)
|
158 |
+
x = self.norm_layers_2[i](x + y)
|
159 |
+
x = x * x_mask
|
160 |
+
return x
|
161 |
+
|
162 |
+
|
163 |
+
class MultiHeadAttention(nn.Module):
|
164 |
+
def __init__(
|
165 |
+
self,
|
166 |
+
channels,
|
167 |
+
out_channels,
|
168 |
+
n_heads,
|
169 |
+
p_dropout=0.,
|
170 |
+
window_size=None,
|
171 |
+
heads_share=True,
|
172 |
+
block_length=None,
|
173 |
+
proximal_bias=False,
|
174 |
+
proximal_init=False
|
175 |
+
):
|
176 |
+
super().__init__()
|
177 |
+
assert channels % n_heads == 0
|
178 |
+
|
179 |
+
self.channels = channels
|
180 |
+
self.out_channels = out_channels
|
181 |
+
self.n_heads = n_heads
|
182 |
+
self.p_dropout = p_dropout
|
183 |
+
self.window_size = window_size
|
184 |
+
self.heads_share = heads_share
|
185 |
+
self.block_length = block_length
|
186 |
+
self.proximal_bias = proximal_bias
|
187 |
+
self.proximal_init = proximal_init
|
188 |
+
self.attn = None
|
189 |
+
|
190 |
+
self.k_channels = channels // n_heads
|
191 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
192 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
193 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
194 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
195 |
+
self.drop = nn.Dropout(p_dropout)
|
196 |
+
|
197 |
+
if window_size is not None:
|
198 |
+
n_heads_rel = 1 if heads_share else n_heads
|
199 |
+
rel_stddev = self.k_channels**-0.5
|
200 |
+
self.emb_rel_k = nn.Parameter(torch.randn(
|
201 |
+
n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
202 |
+
self.emb_rel_v = nn.Parameter(torch.randn(
|
203 |
+
n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
204 |
+
|
205 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
206 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
207 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
208 |
+
if proximal_init:
|
209 |
+
with torch.no_grad():
|
210 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
211 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
212 |
+
|
213 |
+
def forward(self, x, c, attn_mask=None):
|
214 |
+
q = self.conv_q(x)
|
215 |
+
k = self.conv_k(c)
|
216 |
+
v = self.conv_v(c)
|
217 |
+
|
218 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
219 |
+
|
220 |
+
x = self.conv_o(x)
|
221 |
+
return x
|
222 |
+
|
223 |
+
def attention(self, query, key, value, mask=None):
|
224 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
225 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
226 |
+
#query = query.view(
|
227 |
+
# b,
|
228 |
+
# self.n_heads,
|
229 |
+
# self.k_channels,
|
230 |
+
# t_t
|
231 |
+
#).transpose(2, 3) #[b,h,t_t,c], d=h*c
|
232 |
+
#key = key.view(
|
233 |
+
# b,
|
234 |
+
# self.n_heads,
|
235 |
+
# self.k_channels,
|
236 |
+
# t_s
|
237 |
+
#).transpose(2, 3) #[b,h,t_s,c]
|
238 |
+
#value = value.view(
|
239 |
+
# b,
|
240 |
+
# self.n_heads,
|
241 |
+
# self.k_channels,
|
242 |
+
# t_s
|
243 |
+
#).transpose(2, 3) #[b,h,t_s,c]
|
244 |
+
#scores = torch.matmul(
|
245 |
+
# query / math.sqrt(self.k_channels), key.transpose(-2, -1)
|
246 |
+
#) #[b,h,t_t,t_s]
|
247 |
+
query = query.view(
|
248 |
+
b,
|
249 |
+
self.n_heads,
|
250 |
+
self.k_channels,
|
251 |
+
t_t
|
252 |
+
) #[b,h,c,t_t]
|
253 |
+
key = key.view(
|
254 |
+
b,
|
255 |
+
self.n_heads,
|
256 |
+
self.k_channels,
|
257 |
+
t_s
|
258 |
+
) #[b,h,c,t_s]
|
259 |
+
value = value.view(
|
260 |
+
b,
|
261 |
+
self.n_heads,
|
262 |
+
self.k_channels,
|
263 |
+
t_s
|
264 |
+
) #[b,h,c,t_s]
|
265 |
+
scores = torch.einsum('bhdt,bhds -> bhts', query / math.sqrt(self.k_channels), key) #[b,h,t_t,t_s]
|
266 |
+
#if self.window_size is not None:
|
267 |
+
# assert t_s == t_t, "Relative attention is only available for self-attention."
|
268 |
+
# key_relative_embeddings = self._get_relative_embeddings(
|
269 |
+
# self.emb_rel_k, t_s
|
270 |
+
# )
|
271 |
+
# rel_logits = self._matmul_with_relative_keys(
|
272 |
+
# query / math.sqrt(self.k_channels), key_relative_embeddings
|
273 |
+
# ) #[b,h,t_t,d],[h or 1,e,d] ->[b,h,t_t,e]
|
274 |
+
# scores_local = self._relative_position_to_absolute_position(rel_logits)
|
275 |
+
# scores = scores + scores_local
|
276 |
+
#if self.proximal_bias:
|
277 |
+
# assert t_s == t_t, "Proximal bias is only available for self-attention."
|
278 |
+
# scores = scores + \
|
279 |
+
# self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
280 |
+
#if mask is not None:
|
281 |
+
# scores = scores.masked_fill(mask == 0, -1e4)
|
282 |
+
# if self.block_length is not None:
|
283 |
+
# assert t_s == t_t, "Local attention is only available for self-attention."
|
284 |
+
# block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
285 |
+
# scores = scores.masked_fill(block_mask == 0, -1e4)
|
286 |
+
#p_attn = F.softmax(scores, dim=-1) # [b, h, t_t, t_s]
|
287 |
+
#p_attn = self.drop(p_attn)
|
288 |
+
#output = torch.matmul(p_attn, value) # [b,h,t_t,t_s],[b,h,t_s,c] -> [b,h,t_t,c]
|
289 |
+
#if self.window_size is not None:
|
290 |
+
# relative_weights = self._absolute_position_to_relative_position(p_attn) #[b, h, t_t, 2*t_t-1]
|
291 |
+
# value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) #[h or 1, 2*t_t-1, c]
|
292 |
+
# output = output + \
|
293 |
+
# self._matmul_with_relative_values(
|
294 |
+
# relative_weights, value_relative_embeddings) # [b, h, t_t, 2*t_t-1],[h or 1, 2*t_t-1, c] -> [b, h, t_t, c]
|
295 |
+
#output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, c] -> [b,h,c,t_t] -> [b, d, t_t]
|
296 |
+
if self.window_size is not None:
|
297 |
+
assert t_s == t_t, "Relative attention is only available for self-attention."
|
298 |
+
key_relative_embeddings = self._get_relative_embeddings(
|
299 |
+
self.emb_rel_k, t_s
|
300 |
+
)
|
301 |
+
rel_logits = torch.einsum('bhdt,hed->bhte',
|
302 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
303 |
+
) #[b,h,c,t_t],[h or 1,e,c] ->[b,h,t_t,e]
|
304 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
305 |
+
scores = scores + scores_local
|
306 |
+
if self.proximal_bias:
|
307 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
308 |
+
scores = scores + \
|
309 |
+
self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
310 |
+
if mask is not None:
|
311 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
312 |
+
if self.block_length is not None:
|
313 |
+
assert t_s == t_t, "Local attention is only available for self-attention."
|
314 |
+
block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
315 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
316 |
+
p_attn = F.softmax(scores, dim=-1) # [b, h, t_t, t_s]
|
317 |
+
p_attn = self.drop(p_attn)
|
318 |
+
output = torch.einsum('bhcs,bhts->bhct', value , p_attn) # [b,h,c,t_s],[b,h,t_t,t_s] -> [b,h,c,t_t]
|
319 |
+
if self.window_size is not None:
|
320 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn) #[b, h, t_t, 2*t_t-1]
|
321 |
+
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) #[h or 1, 2*t_t-1, c]
|
322 |
+
output = output + \
|
323 |
+
torch.einsum('bhte,hec->bhct',
|
324 |
+
relative_weights, value_relative_embeddings) # [b, h, t_t, 2*t_t-1],[h or 1, 2*t_t-1, c] -> [b, h, c, t_t]
|
325 |
+
output = output.view(b, d, t_t) # [b, h, c, t_t] -> [b, d, t_t]
|
326 |
+
return output, p_attn
|
327 |
+
|
328 |
+
def _matmul_with_relative_values(self, x, y):
|
329 |
+
"""
|
330 |
+
x: [b, h, l, m]
|
331 |
+
y: [h or 1, m, d]
|
332 |
+
ret: [b, h, l, d]
|
333 |
+
"""
|
334 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
335 |
+
return ret
|
336 |
+
|
337 |
+
def _matmul_with_relative_keys(self, x, y):
|
338 |
+
"""
|
339 |
+
x: [b, h, l, d]
|
340 |
+
y: [h or 1, m, d]
|
341 |
+
ret: [b, h, l, m]
|
342 |
+
"""
|
343 |
+
#ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
344 |
+
ret = torch.einsum('bhld,hmd -> bhlm', x, y)
|
345 |
+
return ret
|
346 |
+
|
347 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
348 |
+
max_relative_position = 2 * self.window_size + 1
|
349 |
+
# Pad first before slice to avoid using cond ops.
|
350 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
351 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
352 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
353 |
+
if pad_length > 0:
|
354 |
+
padded_relative_embeddings = F.pad(
|
355 |
+
relative_embeddings,
|
356 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
|
357 |
+
else:
|
358 |
+
padded_relative_embeddings = relative_embeddings
|
359 |
+
used_relative_embeddings = padded_relative_embeddings[
|
360 |
+
:, slice_start_position:slice_end_position
|
361 |
+
]
|
362 |
+
return used_relative_embeddings
|
363 |
+
|
364 |
+
def _relative_position_to_absolute_position(self, x):
|
365 |
+
"""
|
366 |
+
x: [b, h, l, 2*l-1]
|
367 |
+
ret: [b, h, l, l]
|
368 |
+
"""
|
369 |
+
batch, heads, length, _ = x.size()
|
370 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
371 |
+
x = F.pad(x, commons.convert_pad_shape(
|
372 |
+
[[0, 0], [0, 0], [0, 0], [0, 1]]
|
373 |
+
))
|
374 |
+
|
375 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
376 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
377 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape(
|
378 |
+
[[0, 0], [0, 0], [0, length-1]]
|
379 |
+
))
|
380 |
+
|
381 |
+
# Reshape and slice out the padded elements.
|
382 |
+
x_final = x_flat.view([batch, heads, length+1, 2*length-1])[
|
383 |
+
:, :, :length, length-1:
|
384 |
+
]
|
385 |
+
return x_final
|
386 |
+
|
387 |
+
def _absolute_position_to_relative_position(self, x):
|
388 |
+
"""
|
389 |
+
x: [b, h, l, l]
|
390 |
+
ret: [b, h, l, 2*l-1]
|
391 |
+
"""
|
392 |
+
batch, heads, length, _ = x.size()
|
393 |
+
# padd along column
|
394 |
+
x = F.pad(x, commons.convert_pad_shape(
|
395 |
+
[[0, 0], [0, 0], [0, 0], [0, length-1]]
|
396 |
+
))
|
397 |
+
x_flat = x.view([batch, heads, length**2 + length*(length - 1)])
|
398 |
+
# add 0's in the beginning that will skew the elements after reshape
|
399 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape(
|
400 |
+
[[0, 0], [0, 0], [length, 0]]
|
401 |
+
))
|
402 |
+
x_final = x_flat.view([batch, heads, length, 2*length])[:, :, :, 1:]
|
403 |
+
return x_final
|
404 |
+
|
405 |
+
def _attention_bias_proximal(self, length):
|
406 |
+
"""Bias for self-attention to encourage attention to close positions.
|
407 |
+
Args:
|
408 |
+
length: an integer scalar.
|
409 |
+
Returns:
|
410 |
+
a Tensor with shape [1, 1, length, length]
|
411 |
+
"""
|
412 |
+
r = torch.arange(length, dtype=torch.float32)
|
413 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
414 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
415 |
+
|
416 |
+
|
417 |
+
class FFN(nn.Module):
|
418 |
+
def __init__(
|
419 |
+
self,
|
420 |
+
in_channels,
|
421 |
+
out_channels,
|
422 |
+
filter_channels,
|
423 |
+
kernel_size,
|
424 |
+
p_dropout=0.,
|
425 |
+
activation=None,
|
426 |
+
causal=False
|
427 |
+
):
|
428 |
+
super().__init__()
|
429 |
+
self.in_channels = in_channels
|
430 |
+
self.out_channels = out_channels
|
431 |
+
self.filter_channels = filter_channels
|
432 |
+
self.kernel_size = kernel_size
|
433 |
+
self.p_dropout = p_dropout
|
434 |
+
self.activation = activation
|
435 |
+
self.causal = causal
|
436 |
+
|
437 |
+
if causal:
|
438 |
+
self.padding = self._causal_padding
|
439 |
+
else:
|
440 |
+
self.padding = self._same_padding
|
441 |
+
|
442 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
443 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
444 |
+
self.drop = nn.Dropout(p_dropout)
|
445 |
+
|
446 |
+
def forward(self, x, x_mask):
|
447 |
+
x = self.conv_1(self.padding(x * x_mask))
|
448 |
+
if self.activation == "gelu":
|
449 |
+
x = x * torch.sigmoid(1.702 * x)
|
450 |
+
else:
|
451 |
+
x = torch.relu(x)
|
452 |
+
x = self.drop(x)
|
453 |
+
x = self.conv_2(self.padding(x * x_mask))
|
454 |
+
return x * x_mask
|
455 |
+
|
456 |
+
def _causal_padding(self, x):
|
457 |
+
if self.kernel_size == 1:
|
458 |
+
return x
|
459 |
+
pad_l = self.kernel_size - 1
|
460 |
+
pad_r = 0
|
461 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
462 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
463 |
+
return x
|
464 |
+
|
465 |
+
def _same_padding(self, x):
|
466 |
+
if self.kernel_size == 1:
|
467 |
+
return x
|
468 |
+
pad_l = (self.kernel_size - 1) // 2
|
469 |
+
pad_r = self.kernel_size // 2
|
470 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
471 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
472 |
+
return x
|
commons.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
|
7 |
+
def init_weights(m, mean=0.0, std=0.01):
|
8 |
+
classname = m.__class__.__name__
|
9 |
+
if classname.find("Conv") != -1:
|
10 |
+
m.weight.data.normal_(mean, std)
|
11 |
+
|
12 |
+
|
13 |
+
def get_padding(kernel_size, dilation=1):
|
14 |
+
return int((kernel_size * dilation - dilation) / 2)
|
15 |
+
|
16 |
+
|
17 |
+
def convert_pad_shape(pad_shape):
|
18 |
+
l = pad_shape[::-1]
|
19 |
+
pad_shape = [item for sublist in l for item in sublist]
|
20 |
+
return pad_shape
|
21 |
+
|
22 |
+
|
23 |
+
def intersperse(lst, item):
|
24 |
+
result = [item] * (len(lst) * 2 + 1)
|
25 |
+
result[1::2] = lst
|
26 |
+
return result
|
27 |
+
|
28 |
+
|
29 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
30 |
+
"""KL(P||Q)"""
|
31 |
+
kl = (logs_q - logs_p) - 0.5
|
32 |
+
kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
|
33 |
+
return kl
|
34 |
+
|
35 |
+
|
36 |
+
def rand_gumbel(shape):
|
37 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
38 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
39 |
+
return -torch.log(-torch.log(uniform_samples))
|
40 |
+
|
41 |
+
|
42 |
+
def rand_gumbel_like(x):
|
43 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
44 |
+
return g
|
45 |
+
|
46 |
+
|
47 |
+
def slice_segments(x, ids_str, segment_size=4):
|
48 |
+
ret = torch.zeros_like(x[:, :, :segment_size])
|
49 |
+
for i in range(x.size(0)):
|
50 |
+
idx_str = ids_str[i]
|
51 |
+
idx_end = idx_str + segment_size
|
52 |
+
ret[i] = x[i, :, idx_str:idx_end]
|
53 |
+
return ret
|
54 |
+
|
55 |
+
|
56 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
57 |
+
b, d, t = x.size()
|
58 |
+
if x_lengths is None:
|
59 |
+
x_lengths = t
|
60 |
+
ids_str_max = x_lengths - segment_size + 1
|
61 |
+
ids_str = (torch.rand([b]).to(device=x.device)
|
62 |
+
* ids_str_max).to(dtype=torch.long)
|
63 |
+
ids_str = torch.max(torch.zeros(ids_str.size()).to(ids_str.device), ids_str).to(dtype=torch.long)
|
64 |
+
ret = slice_segments(x, ids_str, segment_size)
|
65 |
+
return ret, ids_str
|
66 |
+
|
67 |
+
def rand_slice_segments_for_cat(x, x_lengths=None, segment_size=4):
|
68 |
+
b, d, t = x.size()
|
69 |
+
if x_lengths is None:
|
70 |
+
x_lengths = t
|
71 |
+
ids_str_max = x_lengths - segment_size + 1
|
72 |
+
ids_str = torch.rand([b//2]).to(device=x.device)
|
73 |
+
ids_str = (torch.cat([ids_str,ids_str], dim=0)
|
74 |
+
* ids_str_max).to(dtype=torch.long)
|
75 |
+
ids_str = torch.max(torch.zeros(ids_str.size()).to(ids_str.device), ids_str).to(dtype=torch.long)
|
76 |
+
ret = slice_segments(x, ids_str, segment_size)
|
77 |
+
return ret, ids_str
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
|
82 |
+
def get_timing_signal_1d(
|
83 |
+
length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
84 |
+
position = torch.arange(length, dtype=torch.float)
|
85 |
+
num_timescales = channels // 2
|
86 |
+
log_timescale_increment = (
|
87 |
+
math.log(float(max_timescale) / float(min_timescale)) / (num_timescales - 1)
|
88 |
+
)
|
89 |
+
inv_timescales = min_timescale * torch.exp(
|
90 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
91 |
+
)
|
92 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
93 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
94 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
95 |
+
signal = signal.view(1, channels, length)
|
96 |
+
return signal
|
97 |
+
|
98 |
+
|
99 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
100 |
+
b, channels, length = x.size()
|
101 |
+
signal = get_timing_signal_1d(
|
102 |
+
length, channels, min_timescale, max_timescale
|
103 |
+
)
|
104 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
105 |
+
|
106 |
+
|
107 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
108 |
+
b, channels, length = x.size()
|
109 |
+
signal = get_timing_signal_1d(
|
110 |
+
length, channels, min_timescale, max_timescale
|
111 |
+
)
|
112 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
113 |
+
|
114 |
+
|
115 |
+
def subsequent_mask(length):
|
116 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
117 |
+
return mask
|
118 |
+
|
119 |
+
|
120 |
+
@torch.jit.script
|
121 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
122 |
+
n_channels_int = n_channels[0]
|
123 |
+
in_act = input_a + input_b
|
124 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
125 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
126 |
+
acts = t_act * s_act
|
127 |
+
return acts
|
128 |
+
|
129 |
+
|
130 |
+
def convert_pad_shape(pad_shape):
|
131 |
+
l = pad_shape[::-1]
|
132 |
+
pad_shape = [item for sublist in l for item in sublist]
|
133 |
+
return pad_shape
|
134 |
+
|
135 |
+
|
136 |
+
def shift_1d(x):
|
137 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
138 |
+
return x
|
139 |
+
|
140 |
+
|
141 |
+
def sequence_mask(length, max_length=None):
|
142 |
+
if max_length is None:
|
143 |
+
max_length = length.max()
|
144 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
145 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
146 |
+
|
147 |
+
|
148 |
+
def generate_path(duration, mask):
|
149 |
+
"""
|
150 |
+
duration: [b, 1, t_x]
|
151 |
+
mask: [b, 1, t_y, t_x]
|
152 |
+
"""
|
153 |
+
device = duration.device
|
154 |
+
|
155 |
+
b, _, t_y, t_x = mask.shape
|
156 |
+
cum_duration = torch.cumsum(duration, -1)
|
157 |
+
|
158 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
159 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
160 |
+
path = path.view(b, t_x, t_y)
|
161 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
162 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
163 |
+
return path
|
164 |
+
|
165 |
+
|
166 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
167 |
+
if isinstance(parameters, torch.Tensor):
|
168 |
+
parameters = [parameters]
|
169 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
170 |
+
norm_type = float(norm_type)
|
171 |
+
if clip_value is not None:
|
172 |
+
clip_value = float(clip_value)
|
173 |
+
|
174 |
+
total_norm = 0
|
175 |
+
for p in parameters:
|
176 |
+
param_norm = p.grad.data.norm(norm_type)
|
177 |
+
total_norm += param_norm.item() ** norm_type
|
178 |
+
if clip_value is not None:
|
179 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
180 |
+
total_norm = total_norm ** (1. / norm_type)
|
181 |
+
return total_norm
|
configs/config_en.yaml
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
train:
|
2 |
+
log_interval: 200 # step unit
|
3 |
+
eval_interval: 400 # step unit
|
4 |
+
save_interval: 50 # epoch unit: 50 for baseline / 500 for fine-tuning
|
5 |
+
seed: 1234
|
6 |
+
epochs: 7000
|
7 |
+
learning_rate: 2e-4
|
8 |
+
betas: [0.8, 0.99]
|
9 |
+
eps: 1e-9
|
10 |
+
batch_size: 48
|
11 |
+
fp16_run: True #False
|
12 |
+
lr_decay: 0.999875
|
13 |
+
segment_size: 8192
|
14 |
+
c_mel: 45
|
15 |
+
c_kl: 1.0
|
16 |
+
c_vq: 1.
|
17 |
+
c_commit: 0.2
|
18 |
+
c_yin: 45.
|
19 |
+
log_path: "/pits/logs"
|
20 |
+
n_sample: 3
|
21 |
+
alpha: 200
|
22 |
+
|
23 |
+
data:
|
24 |
+
data_path: "/DATA/audio/VCTK-0.92"
|
25 |
+
training_files: "filelists/vctk_train_g2p.txt"
|
26 |
+
validation_files: "filelists/vctk_val_g2p.txt"
|
27 |
+
languages: "en_US"
|
28 |
+
text_cleaners: ["english_cleaners"]
|
29 |
+
sampling_rate: 22050
|
30 |
+
filter_length: 1024
|
31 |
+
hop_length: 256
|
32 |
+
win_length: 1024
|
33 |
+
n_mel_channels: 80
|
34 |
+
mel_fmin: 0.0
|
35 |
+
mel_fmax: null
|
36 |
+
add_blank: True
|
37 |
+
speakers: ["p225", "p226", "p227", "p228", "p229", "p230", "p231", "p232", "p233", "p234", "p236", "p237", "p238", "p239", "p240", "p241", "p243", "p244", "p245", "p246", "p247", "p248", "p249", "p250", "p251", "p252", "p253", "p254", "p255", "p256", "p257", "p258", "p259", "p260", "p261", "p262", "p263", "p264", "p265", "p266", "p267", "p268", "p269", "p270", "p271", "p272", "p273", "p274", "p275", "p276", "p277", "p278", "p279", "p281", "p282", "p283", "p284", "p285", "p286", "p287", "p288", "p292", "p293", "p294", "p295", "p297", "p298", "p299", "p300", "p301", "p302", "p303", "p304", "p305", "p306", "p307", "p308", "p310", "p311", "p312", "p313", "p314", "p316", "p317", "p318", "p323", "p326", "p329", "p330", "p333", "p334", "p335", "p336", "p339", "p340", "p341", "p343", "p345", "p347", "p351", "p360", "p361", "p362", "p363", "p364", "p374", "p376", "s5"]
|
38 |
+
persistent_workers: True
|
39 |
+
midi_start: -5
|
40 |
+
midi_end: 75
|
41 |
+
midis: 80
|
42 |
+
ying_window: 2048
|
43 |
+
ying_hop: 256
|
44 |
+
tau_max: 2048
|
45 |
+
octave_range: 24
|
46 |
+
|
47 |
+
model:
|
48 |
+
inter_channels: 192
|
49 |
+
hidden_channels: 192
|
50 |
+
filter_channels: 768
|
51 |
+
n_heads: 2
|
52 |
+
n_layers: 6
|
53 |
+
kernel_size: 3
|
54 |
+
p_dropout: 0.1
|
55 |
+
resblock: "1"
|
56 |
+
resblock_kernel_sizes: [3,7,11]
|
57 |
+
resblock_dilation_sizes: [[1,3,5], [1,3,5], [1,3,5]]
|
58 |
+
upsample_rates: [8,8,2,2]
|
59 |
+
upsample_initial_channel: 512
|
60 |
+
upsample_kernel_sizes: [16,16,4,4]
|
61 |
+
n_layers_q: 3
|
62 |
+
use_spectral_norm: False
|
63 |
+
gin_channels: 256
|
64 |
+
codebook_size: 320
|
65 |
+
yin_channels: 80
|
66 |
+
yin_start: 15 # scope start bin in nansy = 1.5/8
|
67 |
+
yin_scope: 50 # scope ratio in nansy = 5/8
|
68 |
+
yin_shift_range: 15 # same as default start index of yingram
|
logs/pits_vctk_AD_3000.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df99b0315cdd3e4e138e46871b86df1e226c4ffc522c3fc2bb44be07fd757821
|
3 |
+
size 763076464
|
models.py
ADDED
@@ -0,0 +1,1383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
# from https://github.com/ncsoft/avocodo
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
from torch.nn import functional as F
|
7 |
+
from torch.nn import Conv1d, ConvTranspose1d, Conv2d
|
8 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
9 |
+
|
10 |
+
import modules
|
11 |
+
import attentions
|
12 |
+
import commons
|
13 |
+
from commons import init_weights, get_padding
|
14 |
+
#for Q option
|
15 |
+
#from functions import vq, vq_st
|
16 |
+
|
17 |
+
from analysis import Pitch
|
18 |
+
from pqmf import PQMF
|
19 |
+
|
20 |
+
|
21 |
+
class StochasticDurationPredictor(nn.Module):
|
22 |
+
|
23 |
+
def __init__(self,
|
24 |
+
in_channels,
|
25 |
+
filter_channels,
|
26 |
+
kernel_size,
|
27 |
+
p_dropout,
|
28 |
+
n_flows=4,
|
29 |
+
gin_channels=0):
|
30 |
+
super().__init__()
|
31 |
+
# it needs to be removed from future version.
|
32 |
+
filter_channels = in_channels
|
33 |
+
self.in_channels = in_channels
|
34 |
+
self.filter_channels = filter_channels
|
35 |
+
self.kernel_size = kernel_size
|
36 |
+
self.p_dropout = p_dropout
|
37 |
+
self.n_flows = n_flows
|
38 |
+
self.gin_channels = gin_channels
|
39 |
+
|
40 |
+
self.log_flow = modules.Log()
|
41 |
+
self.flows = nn.ModuleList()
|
42 |
+
self.flows.append(modules.ElementwiseAffine(2))
|
43 |
+
for i in range(n_flows):
|
44 |
+
self.flows.append(
|
45 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
|
46 |
+
self.flows.append(modules.Flip())
|
47 |
+
|
48 |
+
self.post_pre = nn.Conv1d(1, filter_channels, 1)
|
49 |
+
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
50 |
+
self.post_convs = modules.DDSConv(filter_channels,
|
51 |
+
kernel_size,
|
52 |
+
n_layers=3,
|
53 |
+
p_dropout=p_dropout)
|
54 |
+
self.post_flows = nn.ModuleList()
|
55 |
+
self.post_flows.append(modules.ElementwiseAffine(2))
|
56 |
+
for i in range(4):
|
57 |
+
self.post_flows.append(
|
58 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
|
59 |
+
self.post_flows.append(modules.Flip())
|
60 |
+
|
61 |
+
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
|
62 |
+
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
63 |
+
self.convs = modules.DDSConv(filter_channels,
|
64 |
+
kernel_size,
|
65 |
+
n_layers=3,
|
66 |
+
p_dropout=p_dropout)
|
67 |
+
if gin_channels != 0:
|
68 |
+
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
|
69 |
+
|
70 |
+
def forward(self,
|
71 |
+
x,
|
72 |
+
x_mask,
|
73 |
+
w=None,
|
74 |
+
g=None,
|
75 |
+
reverse=False,
|
76 |
+
noise_scale=1.0):
|
77 |
+
x = torch.detach(x)
|
78 |
+
x = self.pre(x)
|
79 |
+
if g is not None:
|
80 |
+
g = torch.detach(g)
|
81 |
+
x = x + self.cond(g)
|
82 |
+
x = self.convs(x, x_mask)
|
83 |
+
x = self.proj(x) * x_mask
|
84 |
+
|
85 |
+
if not reverse:
|
86 |
+
flows = self.flows
|
87 |
+
assert w is not None
|
88 |
+
|
89 |
+
logdet_tot_q = 0
|
90 |
+
h_w = self.post_pre(w)
|
91 |
+
h_w = self.post_convs(h_w, x_mask)
|
92 |
+
h_w = self.post_proj(h_w) * x_mask
|
93 |
+
e_q = torch.randn(w.size(0), 2, w.size(2)).to(
|
94 |
+
device=x.device, dtype=x.dtype) * x_mask
|
95 |
+
z_q = e_q
|
96 |
+
for flow in self.post_flows:
|
97 |
+
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
|
98 |
+
logdet_tot_q += logdet_q
|
99 |
+
z_u, z1 = torch.split(z_q, [1, 1], 1)
|
100 |
+
u = torch.sigmoid(z_u) * x_mask
|
101 |
+
z0 = (w - u) * x_mask
|
102 |
+
logdet_tot_q += torch.sum(
|
103 |
+
(F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
|
104 |
+
logq = torch.sum(
|
105 |
+
-0.5 * (math.log(2 * math.pi) +
|
106 |
+
(e_q**2)) * x_mask, [1, 2]) - logdet_tot_q
|
107 |
+
|
108 |
+
logdet_tot = 0
|
109 |
+
z0, logdet = self.log_flow(z0, x_mask)
|
110 |
+
logdet_tot += logdet
|
111 |
+
z = torch.cat([z0, z1], 1)
|
112 |
+
for flow in flows:
|
113 |
+
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
|
114 |
+
logdet_tot = logdet_tot + logdet
|
115 |
+
nll = torch.sum(0.5 * (math.log(2 * math.pi) +
|
116 |
+
(z**2)) * x_mask, [1, 2]) - logdet_tot
|
117 |
+
return nll + logq # [b]
|
118 |
+
else:
|
119 |
+
flows = list(reversed(self.flows))
|
120 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
121 |
+
z = torch.randn(x.size(0), 2, x.size(2)).to(
|
122 |
+
device=x.device, dtype=x.dtype) * noise_scale
|
123 |
+
for flow in flows:
|
124 |
+
z = flow(z, x_mask, g=x, reverse=reverse)
|
125 |
+
z0, z1 = torch.split(z, [1, 1], 1)
|
126 |
+
logw = z0
|
127 |
+
return logw
|
128 |
+
|
129 |
+
|
130 |
+
class DurationPredictor(nn.Module):
|
131 |
+
|
132 |
+
def __init__(self,
|
133 |
+
in_channels,
|
134 |
+
filter_channels,
|
135 |
+
kernel_size,
|
136 |
+
p_dropout,
|
137 |
+
gin_channels=0):
|
138 |
+
super().__init__()
|
139 |
+
|
140 |
+
self.in_channels = in_channels
|
141 |
+
self.filter_channels = filter_channels
|
142 |
+
self.kernel_size = kernel_size
|
143 |
+
self.p_dropout = p_dropout
|
144 |
+
self.gin_channels = gin_channels
|
145 |
+
|
146 |
+
self.drop = nn.Dropout(p_dropout)
|
147 |
+
self.conv_1 = nn.Conv1d(in_channels,
|
148 |
+
filter_channels,
|
149 |
+
kernel_size,
|
150 |
+
padding=kernel_size // 2)
|
151 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
152 |
+
self.conv_2 = nn.Conv1d(filter_channels,
|
153 |
+
filter_channels,
|
154 |
+
kernel_size,
|
155 |
+
padding=kernel_size // 2)
|
156 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
157 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
158 |
+
|
159 |
+
if gin_channels != 0:
|
160 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
161 |
+
|
162 |
+
def forward(self, x, x_mask, g=None):
|
163 |
+
x = torch.detach(x)
|
164 |
+
if g is not None:
|
165 |
+
g = torch.detach(g)
|
166 |
+
x = x + self.cond(g)
|
167 |
+
x = self.conv_1(x * x_mask)
|
168 |
+
x = torch.relu(x)
|
169 |
+
x = self.norm_1(x)
|
170 |
+
x = self.drop(x)
|
171 |
+
x = self.conv_2(x * x_mask)
|
172 |
+
x = torch.relu(x)
|
173 |
+
x = self.norm_2(x)
|
174 |
+
x = self.drop(x)
|
175 |
+
x = self.proj(x * x_mask)
|
176 |
+
return x * x_mask
|
177 |
+
|
178 |
+
|
179 |
+
class TextEncoder(nn.Module):
|
180 |
+
|
181 |
+
def __init__(self, n_vocab, out_channels, hidden_channels, filter_channels,
|
182 |
+
n_heads, n_layers, kernel_size, p_dropout):
|
183 |
+
super().__init__()
|
184 |
+
self.n_vocab = n_vocab
|
185 |
+
self.out_channels = out_channels
|
186 |
+
self.hidden_channels = hidden_channels
|
187 |
+
self.filter_channels = filter_channels
|
188 |
+
self.n_heads = n_heads
|
189 |
+
self.n_layers = n_layers
|
190 |
+
self.kernel_size = kernel_size
|
191 |
+
self.p_dropout = p_dropout
|
192 |
+
|
193 |
+
self.emb = nn.Embedding(n_vocab, hidden_channels)
|
194 |
+
nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
|
195 |
+
self.emb_t = nn.Embedding(6, hidden_channels)
|
196 |
+
nn.init.normal_(self.emb_t.weight, 0.0, hidden_channels**-0.5)
|
197 |
+
|
198 |
+
self.encoder = attentions.Encoder(hidden_channels, filter_channels,
|
199 |
+
n_heads, n_layers, kernel_size,
|
200 |
+
p_dropout)
|
201 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
202 |
+
|
203 |
+
def forward(self, x, t, x_lengths):
|
204 |
+
t_zero = (t == 0)
|
205 |
+
emb_t = self.emb_t(t)
|
206 |
+
emb_t[t_zero, :] = 0
|
207 |
+
x = (self.emb(x) + emb_t) * math.sqrt(
|
208 |
+
self.hidden_channels) # [b, t, h]
|
209 |
+
#x = torch.transpose(x, 1, -1) # [b, h, t]
|
210 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(1)),
|
211 |
+
1).to(x.dtype)
|
212 |
+
#x = self.encoder(x * x_mask, x_mask)
|
213 |
+
x = torch.einsum('btd,but->bdt', x, x_mask)
|
214 |
+
x = self.encoder(x, x_mask)
|
215 |
+
stats = self.proj(x) * x_mask
|
216 |
+
|
217 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
218 |
+
return x, m, logs, x_mask
|
219 |
+
|
220 |
+
|
221 |
+
class ResidualCouplingBlock(nn.Module):
|
222 |
+
|
223 |
+
def __init__(self,
|
224 |
+
channels,
|
225 |
+
hidden_channels,
|
226 |
+
kernel_size,
|
227 |
+
dilation_rate,
|
228 |
+
n_layers,
|
229 |
+
n_flows=4,
|
230 |
+
gin_channels=0):
|
231 |
+
super().__init__()
|
232 |
+
self.channels = channels
|
233 |
+
self.hidden_channels = hidden_channels
|
234 |
+
self.kernel_size = kernel_size
|
235 |
+
self.dilation_rate = dilation_rate
|
236 |
+
self.n_layers = n_layers
|
237 |
+
self.n_flows = n_flows
|
238 |
+
self.gin_channels = gin_channels
|
239 |
+
|
240 |
+
self.flows = nn.ModuleList()
|
241 |
+
for i in range(n_flows):
|
242 |
+
self.flows.append(
|
243 |
+
modules.ResidualCouplingLayer(channels,
|
244 |
+
hidden_channels,
|
245 |
+
kernel_size,
|
246 |
+
dilation_rate,
|
247 |
+
n_layers,
|
248 |
+
gin_channels=gin_channels,
|
249 |
+
mean_only=True))
|
250 |
+
self.flows.append(modules.Flip())
|
251 |
+
|
252 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
253 |
+
if not reverse:
|
254 |
+
for flow in self.flows:
|
255 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
256 |
+
else:
|
257 |
+
for flow in reversed(self.flows):
|
258 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
259 |
+
return x
|
260 |
+
|
261 |
+
|
262 |
+
class PosteriorEncoder(nn.Module):
|
263 |
+
|
264 |
+
def __init__(self,
|
265 |
+
in_channels,
|
266 |
+
out_channels,
|
267 |
+
hidden_channels,
|
268 |
+
kernel_size,
|
269 |
+
dilation_rate,
|
270 |
+
n_layers,
|
271 |
+
gin_channels=0):
|
272 |
+
super().__init__()
|
273 |
+
self.in_channels = in_channels
|
274 |
+
self.out_channels = out_channels
|
275 |
+
self.hidden_channels = hidden_channels
|
276 |
+
self.kernel_size = kernel_size
|
277 |
+
self.dilation_rate = dilation_rate
|
278 |
+
self.n_layers = n_layers
|
279 |
+
self.gin_channels = gin_channels
|
280 |
+
|
281 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
282 |
+
self.enc = modules.WN(hidden_channels,
|
283 |
+
kernel_size,
|
284 |
+
dilation_rate,
|
285 |
+
n_layers,
|
286 |
+
gin_channels=gin_channels)
|
287 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
288 |
+
|
289 |
+
def forward(self, x, x_lengths, g=None):
|
290 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)),
|
291 |
+
1).to(x.dtype)
|
292 |
+
x = self.pre(x) * x_mask
|
293 |
+
x = self.enc(x, x_mask, g=g)
|
294 |
+
stats = self.proj(x) * x_mask
|
295 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
296 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
297 |
+
return z, m, logs, x_mask
|
298 |
+
|
299 |
+
|
300 |
+
class Generator(nn.Module):
|
301 |
+
|
302 |
+
def __init__(self,
|
303 |
+
initial_channel,
|
304 |
+
resblock,
|
305 |
+
resblock_kernel_sizes,
|
306 |
+
resblock_dilation_sizes,
|
307 |
+
upsample_rates,
|
308 |
+
upsample_initial_channel,
|
309 |
+
upsample_kernel_sizes,
|
310 |
+
gin_channels=0):
|
311 |
+
super(Generator, self).__init__()
|
312 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
313 |
+
self.num_upsamples = len(upsample_rates)
|
314 |
+
self.conv_pre = Conv1d(initial_channel,
|
315 |
+
upsample_initial_channel,
|
316 |
+
7,
|
317 |
+
1,
|
318 |
+
padding=3)
|
319 |
+
resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
|
320 |
+
|
321 |
+
self.ups = nn.ModuleList()
|
322 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
323 |
+
self.ups.append(
|
324 |
+
weight_norm(
|
325 |
+
ConvTranspose1d(upsample_initial_channel // (2**i),
|
326 |
+
upsample_initial_channel // (2**(i + 1)),
|
327 |
+
k,
|
328 |
+
u,
|
329 |
+
padding=(k - u) // 2)))
|
330 |
+
|
331 |
+
self.resblocks = nn.ModuleList()
|
332 |
+
self.conv_posts = nn.ModuleList()
|
333 |
+
for i in range(len(self.ups)):
|
334 |
+
ch = upsample_initial_channel // (2**(i + 1))
|
335 |
+
for j, (k, d) in enumerate(
|
336 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)):
|
337 |
+
self.resblocks.append(resblock(ch, k, d))
|
338 |
+
if i >= len(self.ups) - 3:
|
339 |
+
self.conv_posts.append(
|
340 |
+
Conv1d(ch, 1, 7, 1, padding=3, bias=False))
|
341 |
+
self.ups.apply(init_weights)
|
342 |
+
|
343 |
+
if gin_channels != 0:
|
344 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
345 |
+
|
346 |
+
def forward(self, x, g=None):
|
347 |
+
x = self.conv_pre(x)
|
348 |
+
if g is not None:
|
349 |
+
x = x + self.cond(g)
|
350 |
+
|
351 |
+
for i in range(self.num_upsamples):
|
352 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
353 |
+
x = self.ups[i](x)
|
354 |
+
xs = None
|
355 |
+
for j in range(self.num_kernels):
|
356 |
+
xs = xs + self.resblocks[i * self.num_kernels + j](x) if xs is not None \
|
357 |
+
else self.resblocks[i * self.num_kernels + j](x)
|
358 |
+
x = xs / self.num_kernels
|
359 |
+
x = F.leaky_relu(x)
|
360 |
+
x = self.conv_posts[-1](x)
|
361 |
+
x = torch.tanh(x)
|
362 |
+
|
363 |
+
return x
|
364 |
+
|
365 |
+
def hier_forward(self, x, g=None):
|
366 |
+
outs = []
|
367 |
+
x = self.conv_pre(x)
|
368 |
+
if g is not None:
|
369 |
+
x = x + self.cond(g)
|
370 |
+
|
371 |
+
for i in range(self.num_upsamples):
|
372 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
373 |
+
x = self.ups[i](x)
|
374 |
+
xs = None
|
375 |
+
for j in range(self.num_kernels):
|
376 |
+
xs = xs + self.resblocks[i * self.num_kernels + j](x) if xs is not None \
|
377 |
+
else self.resblocks[i * self.num_kernels + j](x)
|
378 |
+
x = xs / self.num_kernels
|
379 |
+
if i >= self.num_upsamples - 3:
|
380 |
+
_x = F.leaky_relu(x)
|
381 |
+
_x = self.conv_posts[i - self.num_upsamples + 3](_x)
|
382 |
+
_x = torch.tanh(_x)
|
383 |
+
outs.append(_x)
|
384 |
+
return outs
|
385 |
+
|
386 |
+
def remove_weight_norm(self):
|
387 |
+
print('Removing weight norm...')
|
388 |
+
for l in self.ups:
|
389 |
+
remove_weight_norm(l)
|
390 |
+
for l in self.resblocks:
|
391 |
+
l.remove_weight_norm()
|
392 |
+
|
393 |
+
|
394 |
+
class DiscriminatorP(nn.Module):
|
395 |
+
|
396 |
+
def __init__(self,
|
397 |
+
period,
|
398 |
+
kernel_size=5,
|
399 |
+
stride=3,
|
400 |
+
use_spectral_norm=False):
|
401 |
+
super(DiscriminatorP, self).__init__()
|
402 |
+
self.period = period
|
403 |
+
self.use_spectral_norm = use_spectral_norm
|
404 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
405 |
+
self.convs = nn.ModuleList([
|
406 |
+
norm_f(
|
407 |
+
Conv2d(1,
|
408 |
+
32, (kernel_size, 1), (stride, 1),
|
409 |
+
padding=(get_padding(kernel_size, 1), 0))),
|
410 |
+
norm_f(
|
411 |
+
Conv2d(32,
|
412 |
+
128, (kernel_size, 1), (stride, 1),
|
413 |
+
padding=(get_padding(kernel_size, 1), 0))),
|
414 |
+
norm_f(
|
415 |
+
Conv2d(128,
|
416 |
+
512, (kernel_size, 1), (stride, 1),
|
417 |
+
padding=(get_padding(kernel_size, 1), 0))),
|
418 |
+
norm_f(
|
419 |
+
Conv2d(512,
|
420 |
+
1024, (kernel_size, 1), (stride, 1),
|
421 |
+
padding=(get_padding(kernel_size, 1), 0))),
|
422 |
+
norm_f(
|
423 |
+
Conv2d(1024,
|
424 |
+
1024, (kernel_size, 1),
|
425 |
+
1,
|
426 |
+
padding=(get_padding(kernel_size, 1), 0))),
|
427 |
+
])
|
428 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
429 |
+
|
430 |
+
def forward(self, x):
|
431 |
+
fmap = []
|
432 |
+
|
433 |
+
# 1d to 2d
|
434 |
+
b, c, t = x.shape
|
435 |
+
if t % self.period != 0: # pad first
|
436 |
+
n_pad = self.period - (t % self.period)
|
437 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
438 |
+
t = t + n_pad
|
439 |
+
x = x.view(b, c, t // self.period, self.period)
|
440 |
+
|
441 |
+
for l in self.convs:
|
442 |
+
x = l(x)
|
443 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
444 |
+
fmap.append(x)
|
445 |
+
x = self.conv_post(x)
|
446 |
+
fmap.append(x)
|
447 |
+
x = torch.flatten(x, 1, -1)
|
448 |
+
|
449 |
+
return x, fmap
|
450 |
+
|
451 |
+
|
452 |
+
class DiscriminatorS(nn.Module):
|
453 |
+
|
454 |
+
def __init__(self, use_spectral_norm=False):
|
455 |
+
super(DiscriminatorS, self).__init__()
|
456 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
457 |
+
self.convs = nn.ModuleList([
|
458 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
459 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
460 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
461 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
462 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
463 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
464 |
+
])
|
465 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
466 |
+
|
467 |
+
def forward(self, x):
|
468 |
+
fmap = []
|
469 |
+
|
470 |
+
for l in self.convs:
|
471 |
+
x = l(x)
|
472 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
473 |
+
fmap.append(x)
|
474 |
+
x = self.conv_post(x)
|
475 |
+
fmap.append(x)
|
476 |
+
x = torch.flatten(x, 1, -1)
|
477 |
+
|
478 |
+
return x, fmap
|
479 |
+
|
480 |
+
|
481 |
+
class MultiPeriodDiscriminator(nn.Module):
|
482 |
+
|
483 |
+
def __init__(self, use_spectral_norm=False):
|
484 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
485 |
+
periods = [2, 3, 5, 7, 11]
|
486 |
+
|
487 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
488 |
+
discs = discs + \
|
489 |
+
[DiscriminatorP(i, use_spectral_norm=use_spectral_norm)
|
490 |
+
for i in periods]
|
491 |
+
self.discriminators = nn.ModuleList(discs)
|
492 |
+
|
493 |
+
def forward(self, y, y_hat):
|
494 |
+
y_d_rs = []
|
495 |
+
y_d_gs = []
|
496 |
+
fmap_rs = []
|
497 |
+
fmap_gs = []
|
498 |
+
for i, d in enumerate(self.discriminators):
|
499 |
+
y_d_r, fmap_r = d(y)
|
500 |
+
y_d_g, fmap_g = d(y_hat)
|
501 |
+
y_d_rs.append(y_d_r)
|
502 |
+
y_d_gs.append(y_d_g)
|
503 |
+
fmap_rs.append(fmap_r)
|
504 |
+
fmap_gs.append(fmap_g)
|
505 |
+
|
506 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
507 |
+
|
508 |
+
|
509 |
+
##### Avocodo
|
510 |
+
class CoMBDBlock(torch.nn.Module):
|
511 |
+
|
512 |
+
def __init__(
|
513 |
+
self,
|
514 |
+
h_u, # List[int],
|
515 |
+
d_k, # List[int],
|
516 |
+
d_s, # List[int],
|
517 |
+
d_d, # List[int],
|
518 |
+
d_g, # List[int],
|
519 |
+
d_p, # List[int],
|
520 |
+
op_f, # int,
|
521 |
+
op_k, # int,
|
522 |
+
op_g, # int,
|
523 |
+
use_spectral_norm=False):
|
524 |
+
super(CoMBDBlock, self).__init__()
|
525 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
526 |
+
|
527 |
+
self.convs = nn.ModuleList()
|
528 |
+
filters = [[1, h_u[0]]]
|
529 |
+
for i in range(len(h_u) - 1):
|
530 |
+
filters.append([h_u[i], h_u[i + 1]])
|
531 |
+
for _f, _k, _s, _d, _g, _p in zip(filters, d_k, d_s, d_d, d_g, d_p):
|
532 |
+
self.convs.append(
|
533 |
+
norm_f(
|
534 |
+
Conv1d(in_channels=_f[0],
|
535 |
+
out_channels=_f[1],
|
536 |
+
kernel_size=_k,
|
537 |
+
stride=_s,
|
538 |
+
dilation=_d,
|
539 |
+
groups=_g,
|
540 |
+
padding=_p)))
|
541 |
+
self.projection_conv = norm_f(
|
542 |
+
Conv1d(in_channels=filters[-1][1],
|
543 |
+
out_channels=op_f,
|
544 |
+
kernel_size=op_k,
|
545 |
+
groups=op_g))
|
546 |
+
|
547 |
+
def forward(self, x, b_y, b_y_hat):
|
548 |
+
fmap_r = []
|
549 |
+
fmap_g = []
|
550 |
+
for block in self.convs:
|
551 |
+
x = block(x)
|
552 |
+
x = F.leaky_relu(x, 0.2)
|
553 |
+
f_r, f_g = x.split([b_y, b_y_hat], dim=0)
|
554 |
+
fmap_r.append(f_r.tile([2, 1, 1]) if b_y < b_y_hat else f_r)
|
555 |
+
fmap_g.append(f_g)
|
556 |
+
x = self.projection_conv(x)
|
557 |
+
x_r, x_g = x.split([b_y, b_y_hat], dim=0)
|
558 |
+
return x_r.tile([2, 1, 1
|
559 |
+
]) if b_y < b_y_hat else x_r, x_g, fmap_r, fmap_g
|
560 |
+
|
561 |
+
|
562 |
+
class CoMBD(torch.nn.Module):
|
563 |
+
|
564 |
+
def __init__(self, use_spectral_norm=False):
|
565 |
+
super(CoMBD, self).__init__()
|
566 |
+
self.pqmf_list = nn.ModuleList([
|
567 |
+
PQMF(4, 192, 0.13, 10.0), #lv2
|
568 |
+
PQMF(2, 256, 0.25, 10.0) #lv1
|
569 |
+
])
|
570 |
+
combd_h_u = [[16, 64, 256, 1024, 1024, 1024] for _ in range(3)]
|
571 |
+
combd_d_k = [[7, 11, 11, 11, 11, 5], [11, 21, 21, 21, 21, 5],
|
572 |
+
[15, 41, 41, 41, 41, 5]]
|
573 |
+
combd_d_s = [[1, 1, 4, 4, 4, 1] for _ in range(3)]
|
574 |
+
combd_d_d = [[1, 1, 1, 1, 1, 1] for _ in range(3)]
|
575 |
+
combd_d_g = [[1, 4, 16, 64, 256, 1] for _ in range(3)]
|
576 |
+
|
577 |
+
combd_d_p = [[3, 5, 5, 5, 5, 2], [5, 10, 10, 10, 10, 2],
|
578 |
+
[7, 20, 20, 20, 20, 2]]
|
579 |
+
combd_op_f = [1, 1, 1]
|
580 |
+
combd_op_k = [3, 3, 3]
|
581 |
+
combd_op_g = [1, 1, 1]
|
582 |
+
|
583 |
+
self.blocks = nn.ModuleList()
|
584 |
+
for _h_u, _d_k, _d_s, _d_d, _d_g, _d_p, _op_f, _op_k, _op_g in zip(
|
585 |
+
combd_h_u,
|
586 |
+
combd_d_k,
|
587 |
+
combd_d_s,
|
588 |
+
combd_d_d,
|
589 |
+
combd_d_g,
|
590 |
+
combd_d_p,
|
591 |
+
combd_op_f,
|
592 |
+
combd_op_k,
|
593 |
+
combd_op_g,
|
594 |
+
):
|
595 |
+
self.blocks.append(
|
596 |
+
CoMBDBlock(
|
597 |
+
_h_u,
|
598 |
+
_d_k,
|
599 |
+
_d_s,
|
600 |
+
_d_d,
|
601 |
+
_d_g,
|
602 |
+
_d_p,
|
603 |
+
_op_f,
|
604 |
+
_op_k,
|
605 |
+
_op_g,
|
606 |
+
))
|
607 |
+
|
608 |
+
def _block_forward(self, ys, ys_hat, blocks):
|
609 |
+
outs_real = []
|
610 |
+
outs_fake = []
|
611 |
+
f_maps_real = []
|
612 |
+
f_maps_fake = []
|
613 |
+
for y, y_hat, block in zip(ys, ys_hat,
|
614 |
+
blocks): #y:B, y_hat: 2B if i!=-1 else B,B
|
615 |
+
b_y = y.shape[0]
|
616 |
+
b_y_hat = y_hat.shape[0]
|
617 |
+
cat_y = torch.cat([y, y_hat], dim=0)
|
618 |
+
out_real, out_fake, f_map_r, f_map_g = block(cat_y, b_y, b_y_hat)
|
619 |
+
outs_real.append(out_real)
|
620 |
+
outs_fake.append(out_fake)
|
621 |
+
f_maps_real.append(f_map_r)
|
622 |
+
f_maps_fake.append(f_map_g)
|
623 |
+
return outs_real, outs_fake, f_maps_real, f_maps_fake
|
624 |
+
|
625 |
+
def _pqmf_forward(self, ys, ys_hat):
|
626 |
+
# preprocess for multi_scale forward
|
627 |
+
multi_scale_inputs_hat = []
|
628 |
+
for pqmf_ in self.pqmf_list:
|
629 |
+
multi_scale_inputs_hat.append(pqmf_.analysis(ys_hat[-1])[:, :1, :])
|
630 |
+
|
631 |
+
# real
|
632 |
+
# for hierarchical forward
|
633 |
+
#outs_real_, f_maps_real_ = self._block_forward(
|
634 |
+
# ys, self.blocks)
|
635 |
+
|
636 |
+
# for multi_scale forward
|
637 |
+
#outs_real, f_maps_real = self._block_forward(
|
638 |
+
# ys[:-1], self.blocks[:-1], outs_real, f_maps_real)
|
639 |
+
#outs_real.extend(outs_real[:-1])
|
640 |
+
#f_maps_real.extend(f_maps_real[:-1])
|
641 |
+
|
642 |
+
#outs_real = [torch.cat([o,o], dim=0) if i!=len(outs_real_)-1 else o for i,o in enumerate(outs_real_)]
|
643 |
+
#f_maps_real = [[torch.cat([fmap,fmap], dim=0) if i!=len(f_maps_real_)-1 else fmap for fmap in fmaps ] \
|
644 |
+
# for i,fmaps in enumerate(f_maps_real_)]
|
645 |
+
|
646 |
+
inputs_fake = [
|
647 |
+
torch.cat([y, multi_scale_inputs_hat[i]], dim=0)
|
648 |
+
if i != len(ys_hat) - 1 else y for i, y in enumerate(ys_hat)
|
649 |
+
]
|
650 |
+
outs_real, outs_fake, f_maps_real, f_maps_fake = self._block_forward(
|
651 |
+
ys, inputs_fake, self.blocks)
|
652 |
+
|
653 |
+
# predicted
|
654 |
+
# for hierarchical forward
|
655 |
+
#outs_fake, f_maps_fake = self._block_forward(
|
656 |
+
# inputs_fake, self.blocks)
|
657 |
+
|
658 |
+
#outs_real_, f_maps_real_ = self._block_forward(
|
659 |
+
# ys, self.blocks)
|
660 |
+
# for multi_scale forward
|
661 |
+
#outs_fake, f_maps_fake = self._block_forward(
|
662 |
+
# multi_scale_inputs_hat, self.blocks[:-1], outs_fake, f_maps_fake)
|
663 |
+
|
664 |
+
return outs_real, outs_fake, f_maps_real, f_maps_fake
|
665 |
+
|
666 |
+
def forward(self, ys, ys_hat):
|
667 |
+
outs_real, outs_fake, f_maps_real, f_maps_fake = self._pqmf_forward(
|
668 |
+
ys, ys_hat)
|
669 |
+
return outs_real, outs_fake, f_maps_real, f_maps_fake
|
670 |
+
|
671 |
+
|
672 |
+
class MDC(torch.nn.Module):
|
673 |
+
|
674 |
+
def __init__(self,
|
675 |
+
in_channels,
|
676 |
+
out_channels,
|
677 |
+
strides,
|
678 |
+
kernel_size,
|
679 |
+
dilations,
|
680 |
+
use_spectral_norm=False):
|
681 |
+
super(MDC, self).__init__()
|
682 |
+
norm_f = weight_norm if not use_spectral_norm else spectral_norm
|
683 |
+
self.d_convs = nn.ModuleList()
|
684 |
+
for _k, _d in zip(kernel_size, dilations):
|
685 |
+
self.d_convs.append(
|
686 |
+
norm_f(
|
687 |
+
Conv1d(in_channels=in_channels,
|
688 |
+
out_channels=out_channels,
|
689 |
+
kernel_size=_k,
|
690 |
+
dilation=_d,
|
691 |
+
padding=get_padding(_k, _d))))
|
692 |
+
self.post_conv = norm_f(
|
693 |
+
Conv1d(in_channels=out_channels,
|
694 |
+
out_channels=out_channels,
|
695 |
+
kernel_size=3,
|
696 |
+
stride=strides,
|
697 |
+
padding=get_padding(_k, _d)))
|
698 |
+
self.softmax = torch.nn.Softmax(dim=-1)
|
699 |
+
|
700 |
+
def forward(self, x):
|
701 |
+
_out = None
|
702 |
+
for _l in self.d_convs:
|
703 |
+
_x = torch.unsqueeze(_l(x), -1)
|
704 |
+
_x = F.leaky_relu(_x, 0.2)
|
705 |
+
_out = torch.cat([_out, _x], axis=-1) if _out is not None \
|
706 |
+
else _x
|
707 |
+
x = torch.sum(_out, dim=-1)
|
708 |
+
x = self.post_conv(x)
|
709 |
+
x = F.leaky_relu(x, 0.2) # @@
|
710 |
+
|
711 |
+
return x
|
712 |
+
|
713 |
+
|
714 |
+
class SBDBlock(torch.nn.Module):
|
715 |
+
|
716 |
+
def __init__(self,
|
717 |
+
segment_dim,
|
718 |
+
strides,
|
719 |
+
filters,
|
720 |
+
kernel_size,
|
721 |
+
dilations,
|
722 |
+
use_spectral_norm=False):
|
723 |
+
super(SBDBlock, self).__init__()
|
724 |
+
norm_f = weight_norm if not use_spectral_norm else spectral_norm
|
725 |
+
self.convs = nn.ModuleList()
|
726 |
+
filters_in_out = [(segment_dim, filters[0])]
|
727 |
+
for i in range(len(filters) - 1):
|
728 |
+
filters_in_out.append([filters[i], filters[i + 1]])
|
729 |
+
|
730 |
+
for _s, _f, _k, _d in zip(strides, filters_in_out, kernel_size,
|
731 |
+
dilations):
|
732 |
+
self.convs.append(
|
733 |
+
MDC(in_channels=_f[0],
|
734 |
+
out_channels=_f[1],
|
735 |
+
strides=_s,
|
736 |
+
kernel_size=_k,
|
737 |
+
dilations=_d,
|
738 |
+
use_spectral_norm=use_spectral_norm))
|
739 |
+
self.post_conv = norm_f(
|
740 |
+
Conv1d(in_channels=_f[1],
|
741 |
+
out_channels=1,
|
742 |
+
kernel_size=3,
|
743 |
+
stride=1,
|
744 |
+
padding=3 // 2)) # @@
|
745 |
+
|
746 |
+
def forward(self, x):
|
747 |
+
fmap_r = []
|
748 |
+
fmap_g = []
|
749 |
+
for _l in self.convs:
|
750 |
+
x = _l(x)
|
751 |
+
f_r, f_g = torch.chunk(x, 2, dim=0)
|
752 |
+
fmap_r.append(f_r)
|
753 |
+
fmap_g.append(f_g)
|
754 |
+
x = self.post_conv(x) # @@
|
755 |
+
x_r, x_g = torch.chunk(x, 2, dim=0)
|
756 |
+
return x_r, x_g, fmap_r, fmap_g
|
757 |
+
|
758 |
+
|
759 |
+
class MDCDConfig:
|
760 |
+
|
761 |
+
def __init__(self):
|
762 |
+
self.pqmf_params = [16, 256, 0.03, 10.0]
|
763 |
+
self.f_pqmf_params = [64, 256, 0.1, 9.0]
|
764 |
+
self.filters = [[64, 128, 256, 256, 256], [64, 128, 256, 256, 256],
|
765 |
+
[64, 128, 256, 256, 256], [32, 64, 128, 128, 128]]
|
766 |
+
self.kernel_sizes = [[[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7],
|
767 |
+
[7, 7, 7]],
|
768 |
+
[[5, 5, 5], [5, 5, 5], [5, 5, 5], [5, 5, 5],
|
769 |
+
[5, 5, 5]],
|
770 |
+
[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3],
|
771 |
+
[3, 3, 3]],
|
772 |
+
[[5, 5, 5], [5, 5, 5], [5, 5, 5], [5, 5, 5],
|
773 |
+
[5, 5, 5]]]
|
774 |
+
self.dilations = [[[5, 7, 11], [5, 7, 11], [5, 7, 11], [5, 7, 11],
|
775 |
+
[5, 7, 11]],
|
776 |
+
[[3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7],
|
777 |
+
[3, 5, 7]],
|
778 |
+
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3],
|
779 |
+
[1, 2, 3]],
|
780 |
+
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3, 5],
|
781 |
+
[2, 3, 5]]]
|
782 |
+
self.strides = [[1, 1, 3, 3, 1], [1, 1, 3, 3, 1], [1, 1, 3, 3, 1],
|
783 |
+
[1, 1, 3, 3, 1]]
|
784 |
+
self.band_ranges = [[0, 6], [0, 11], [0, 16], [0, 64]]
|
785 |
+
self.transpose = [False, False, False, True]
|
786 |
+
self.segment_size = 8192
|
787 |
+
|
788 |
+
|
789 |
+
class SBD(torch.nn.Module):
|
790 |
+
|
791 |
+
def __init__(self, use_spectral_norm=False):
|
792 |
+
super(SBD, self).__init__()
|
793 |
+
self.config = MDCDConfig()
|
794 |
+
self.pqmf = PQMF(*self.config.pqmf_params)
|
795 |
+
if True in self.config.transpose:
|
796 |
+
self.f_pqmf = PQMF(*self.config.f_pqmf_params)
|
797 |
+
else:
|
798 |
+
self.f_pqmf = None
|
799 |
+
|
800 |
+
self.discriminators = torch.nn.ModuleList()
|
801 |
+
|
802 |
+
for _f, _k, _d, _s, _br, _tr in zip(self.config.filters,
|
803 |
+
self.config.kernel_sizes,
|
804 |
+
self.config.dilations,
|
805 |
+
self.config.strides,
|
806 |
+
self.config.band_ranges,
|
807 |
+
self.config.transpose):
|
808 |
+
if _tr:
|
809 |
+
segment_dim = self.config.segment_size // _br[1] - _br[0]
|
810 |
+
else:
|
811 |
+
segment_dim = _br[1] - _br[0]
|
812 |
+
|
813 |
+
self.discriminators.append(
|
814 |
+
SBDBlock(segment_dim=segment_dim,
|
815 |
+
filters=_f,
|
816 |
+
kernel_size=_k,
|
817 |
+
dilations=_d,
|
818 |
+
strides=_s,
|
819 |
+
use_spectral_norm=use_spectral_norm))
|
820 |
+
|
821 |
+
def forward(self, y, y_hat):
|
822 |
+
y_d_rs = []
|
823 |
+
y_d_gs = []
|
824 |
+
fmap_rs = []
|
825 |
+
fmap_gs = []
|
826 |
+
y_in = self.pqmf.analysis(y)
|
827 |
+
y_hat_in = self.pqmf.analysis(y_hat)
|
828 |
+
y_in_f = self.f_pqmf.analysis(y)
|
829 |
+
y_hat_in_f = self.f_pqmf.analysis(y_hat)
|
830 |
+
|
831 |
+
for d, br, tr in zip(self.discriminators, self.config.band_ranges,
|
832 |
+
self.config.transpose):
|
833 |
+
if not tr:
|
834 |
+
_y_in = y_in[:, br[0]:br[1], :]
|
835 |
+
_y_hat_in = y_hat_in[:, br[0]:br[1], :]
|
836 |
+
else:
|
837 |
+
_y_in = y_in_f[:, br[0]:br[1], :]
|
838 |
+
_y_hat_in = y_hat_in_f[:, br[0]:br[1], :]
|
839 |
+
_y_in = torch.transpose(_y_in, 1, 2)
|
840 |
+
_y_hat_in = torch.transpose(_y_hat_in, 1, 2)
|
841 |
+
#y_d_r, fmap_r = d(_y_in)
|
842 |
+
#y_d_g, fmap_g = d(_y_hat_in)
|
843 |
+
cat_y = torch.cat([_y_in, _y_hat_in], dim=0)
|
844 |
+
y_d_r, y_d_g, fmap_r, fmap_g = d(cat_y)
|
845 |
+
y_d_rs.append(y_d_r)
|
846 |
+
fmap_rs.append(fmap_r)
|
847 |
+
y_d_gs.append(y_d_g)
|
848 |
+
fmap_gs.append(fmap_g)
|
849 |
+
|
850 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
851 |
+
|
852 |
+
|
853 |
+
class AvocodoDiscriminator(nn.Module):
|
854 |
+
|
855 |
+
def __init__(self, use_spectral_norm=False):
|
856 |
+
super(AvocodoDiscriminator, self).__init__()
|
857 |
+
self.combd = CoMBD(use_spectral_norm)
|
858 |
+
self.sbd = SBD(use_spectral_norm)
|
859 |
+
|
860 |
+
def forward(self, y, ys_hat):
|
861 |
+
ys = [
|
862 |
+
self.combd.pqmf_list[0].analysis(y)[:, :1], #lv2
|
863 |
+
self.combd.pqmf_list[1].analysis(y)[:, :1], #lv1
|
864 |
+
y
|
865 |
+
]
|
866 |
+
y_c_rs, y_c_gs, fmap_c_rs, fmap_c_gs = self.combd(ys, ys_hat)
|
867 |
+
y_s_rs, y_s_gs, fmap_s_rs, fmap_s_gs = self.sbd(y, ys_hat[-1])
|
868 |
+
y_c_rs.extend(y_s_rs)
|
869 |
+
y_c_gs.extend(y_s_gs)
|
870 |
+
fmap_c_rs.extend(fmap_s_rs)
|
871 |
+
fmap_c_gs.extend(fmap_s_gs)
|
872 |
+
return y_c_rs, y_c_gs, fmap_c_rs, fmap_c_gs
|
873 |
+
|
874 |
+
|
875 |
+
##### Avocodo
|
876 |
+
|
877 |
+
|
878 |
+
class YingDecoder(nn.Module):
|
879 |
+
|
880 |
+
def __init__(self,
|
881 |
+
hidden_channels,
|
882 |
+
kernel_size,
|
883 |
+
dilation_rate,
|
884 |
+
n_layers,
|
885 |
+
yin_start,
|
886 |
+
yin_scope,
|
887 |
+
yin_shift_range,
|
888 |
+
gin_channels=0):
|
889 |
+
super().__init__()
|
890 |
+
self.in_channels = yin_scope
|
891 |
+
self.out_channels = yin_scope
|
892 |
+
self.hidden_channels = hidden_channels
|
893 |
+
self.kernel_size = kernel_size
|
894 |
+
self.dilation_rate = dilation_rate
|
895 |
+
self.n_layers = n_layers
|
896 |
+
self.gin_channels = gin_channels
|
897 |
+
|
898 |
+
self.yin_start = yin_start
|
899 |
+
self.yin_scope = yin_scope
|
900 |
+
self.yin_shift_range = yin_shift_range
|
901 |
+
|
902 |
+
self.pre = nn.Conv1d(self.in_channels, hidden_channels, 1)
|
903 |
+
self.dec = modules.WN(hidden_channels,
|
904 |
+
kernel_size,
|
905 |
+
dilation_rate,
|
906 |
+
n_layers,
|
907 |
+
gin_channels=gin_channels)
|
908 |
+
self.proj = nn.Conv1d(hidden_channels, self.out_channels, 1)
|
909 |
+
|
910 |
+
def crop_scope(self, x, yin_start,
|
911 |
+
scope_shift): # x: tensor [B,C,T] #scope_shift: tensor [B]
|
912 |
+
return torch.stack([
|
913 |
+
x[i, yin_start + scope_shift[i]:yin_start + self.yin_scope +
|
914 |
+
scope_shift[i], :] for i in range(x.shape[0])
|
915 |
+
],
|
916 |
+
dim=0)
|
917 |
+
|
918 |
+
def infer(self, z_yin, z_mask, g=None):
|
919 |
+
B = z_yin.shape[0]
|
920 |
+
scope_shift = torch.randint(-self.yin_shift_range,
|
921 |
+
self.yin_shift_range, (B, ),
|
922 |
+
dtype=torch.int)
|
923 |
+
z_yin_crop = self.crop_scope(z_yin, self.yin_start, scope_shift)
|
924 |
+
x = self.pre(z_yin_crop) * z_mask
|
925 |
+
x = self.dec(x, z_mask, g=g)
|
926 |
+
yin_hat_crop = self.proj(x) * z_mask
|
927 |
+
return yin_hat_crop
|
928 |
+
|
929 |
+
def forward(self, z_yin, yin_gt, z_mask, g=None):
|
930 |
+
B = z_yin.shape[0]
|
931 |
+
scope_shift = torch.randint(-self.yin_shift_range,
|
932 |
+
self.yin_shift_range, (B, ),
|
933 |
+
dtype=torch.int)
|
934 |
+
z_yin_crop = self.crop_scope(z_yin, self.yin_start, scope_shift)
|
935 |
+
yin_gt_shifted_crop = self.crop_scope(yin_gt, self.yin_start,
|
936 |
+
scope_shift)
|
937 |
+
yin_gt_crop = self.crop_scope(yin_gt, self.yin_start,
|
938 |
+
torch.zeros_like(scope_shift))
|
939 |
+
x = self.pre(z_yin_crop) * z_mask
|
940 |
+
x = self.dec(x, z_mask, g=g)
|
941 |
+
yin_hat_crop = self.proj(x) * z_mask
|
942 |
+
return yin_gt_crop, yin_gt_shifted_crop, yin_hat_crop, z_yin_crop, scope_shift
|
943 |
+
|
944 |
+
|
945 |
+
# For Q option
|
946 |
+
#class VQEmbedding(nn.Module):
|
947 |
+
#
|
948 |
+
# def __init__(self, codebook_size,
|
949 |
+
# code_channels):
|
950 |
+
# super().__init__()
|
951 |
+
# self.embedding = nn.Embedding(codebook_size, code_channels)
|
952 |
+
# self.embedding.weight.data.uniform_(-1. / codebook_size,
|
953 |
+
# 1. / codebook_size)
|
954 |
+
#
|
955 |
+
# def forward(self, z_e_x):
|
956 |
+
# z_e_x_ = z_e_x.permute(0, 2, 1).contiguous()
|
957 |
+
# latent_indices = vq(z_e_x_, self.embedding.weight)
|
958 |
+
# z_q = self.embedding(latent_indices).permute(0, 2, 1)
|
959 |
+
# return z_q
|
960 |
+
#
|
961 |
+
# def straight_through(self, z_e_x):
|
962 |
+
# z_e_x_ = z_e_x.permute(0, 2, 1).contiguous()
|
963 |
+
# z_q_x_st_, indices = vq_st(z_e_x_, self.embedding.weight.detach())
|
964 |
+
# z_q_x_st = z_q_x_st_.permute(0, 2, 1).contiguous()
|
965 |
+
#
|
966 |
+
# z_q_x_flatten = torch.index_select(self.embedding.weight,
|
967 |
+
# dim=0,
|
968 |
+
# index=indices)
|
969 |
+
# z_q_x_ = z_q_x_flatten.view_as(z_e_x_)
|
970 |
+
# z_q_x = z_q_x_.permute(0, 2, 1).contiguous()
|
971 |
+
# return z_q_x_st, z_q_x
|
972 |
+
|
973 |
+
|
974 |
+
class SynthesizerTrn(nn.Module):
|
975 |
+
"""
|
976 |
+
Synthesizer for Training
|
977 |
+
"""
|
978 |
+
|
979 |
+
def __init__(
|
980 |
+
self,
|
981 |
+
n_vocab,
|
982 |
+
spec_channels,
|
983 |
+
segment_size,
|
984 |
+
midi_start,
|
985 |
+
midi_end,
|
986 |
+
octave_range,
|
987 |
+
inter_channels,
|
988 |
+
hidden_channels,
|
989 |
+
filter_channels,
|
990 |
+
n_heads,
|
991 |
+
n_layers,
|
992 |
+
kernel_size,
|
993 |
+
p_dropout,
|
994 |
+
resblock,
|
995 |
+
resblock_kernel_sizes,
|
996 |
+
resblock_dilation_sizes,
|
997 |
+
upsample_rates,
|
998 |
+
upsample_initial_channel,
|
999 |
+
upsample_kernel_sizes,
|
1000 |
+
yin_channels,
|
1001 |
+
yin_start,
|
1002 |
+
yin_scope,
|
1003 |
+
yin_shift_range,
|
1004 |
+
n_speakers=0,
|
1005 |
+
gin_channels=0,
|
1006 |
+
use_sdp=True,
|
1007 |
+
#codebook_size=256, #for Q option
|
1008 |
+
**kwargs):
|
1009 |
+
|
1010 |
+
super().__init__()
|
1011 |
+
self.n_vocab = n_vocab
|
1012 |
+
self.spec_channels = spec_channels
|
1013 |
+
self.inter_channels = inter_channels
|
1014 |
+
self.hidden_channels = hidden_channels
|
1015 |
+
self.filter_channels = filter_channels
|
1016 |
+
self.n_heads = n_heads
|
1017 |
+
self.n_layers = n_layers
|
1018 |
+
self.kernel_size = kernel_size
|
1019 |
+
self.p_dropout = p_dropout
|
1020 |
+
self.resblock = resblock
|
1021 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
1022 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
1023 |
+
self.upsample_rates = upsample_rates
|
1024 |
+
self.upsample_initial_channel = upsample_initial_channel
|
1025 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
1026 |
+
self.segment_size = segment_size
|
1027 |
+
self.n_speakers = n_speakers
|
1028 |
+
self.gin_channels = gin_channels
|
1029 |
+
|
1030 |
+
self.yin_channels = yin_channels
|
1031 |
+
self.yin_start = yin_start
|
1032 |
+
self.yin_scope = yin_scope
|
1033 |
+
|
1034 |
+
self.use_sdp = use_sdp
|
1035 |
+
self.enc_p = TextEncoder(n_vocab, inter_channels, hidden_channels,
|
1036 |
+
filter_channels, n_heads, n_layers,
|
1037 |
+
kernel_size, p_dropout)
|
1038 |
+
self.dec = Generator(
|
1039 |
+
inter_channels - yin_channels +
|
1040 |
+
yin_scope,
|
1041 |
+
resblock,
|
1042 |
+
resblock_kernel_sizes,
|
1043 |
+
resblock_dilation_sizes,
|
1044 |
+
upsample_rates,
|
1045 |
+
upsample_initial_channel,
|
1046 |
+
upsample_kernel_sizes,
|
1047 |
+
gin_channels=gin_channels)
|
1048 |
+
|
1049 |
+
self.enc_spec = PosteriorEncoder(spec_channels,
|
1050 |
+
inter_channels - yin_channels,
|
1051 |
+
inter_channels - yin_channels,
|
1052 |
+
5,
|
1053 |
+
1,
|
1054 |
+
16,
|
1055 |
+
gin_channels=gin_channels)
|
1056 |
+
|
1057 |
+
self.enc_pitch = PosteriorEncoder(yin_channels,
|
1058 |
+
yin_channels,
|
1059 |
+
yin_channels,
|
1060 |
+
5,
|
1061 |
+
1,
|
1062 |
+
16,
|
1063 |
+
gin_channels=gin_channels)
|
1064 |
+
|
1065 |
+
self.flow = ResidualCouplingBlock(inter_channels,
|
1066 |
+
hidden_channels,
|
1067 |
+
5,
|
1068 |
+
1,
|
1069 |
+
4,
|
1070 |
+
gin_channels=gin_channels)
|
1071 |
+
|
1072 |
+
if use_sdp:
|
1073 |
+
self.dp = StochasticDurationPredictor(hidden_channels,
|
1074 |
+
192,
|
1075 |
+
3,
|
1076 |
+
0.5,
|
1077 |
+
4,
|
1078 |
+
gin_channels=gin_channels)
|
1079 |
+
else:
|
1080 |
+
self.dp = DurationPredictor(hidden_channels,
|
1081 |
+
256,
|
1082 |
+
3,
|
1083 |
+
0.5,
|
1084 |
+
gin_channels=gin_channels)
|
1085 |
+
|
1086 |
+
self.yin_dec = YingDecoder(yin_scope,
|
1087 |
+
5,
|
1088 |
+
1,
|
1089 |
+
4,
|
1090 |
+
yin_start,
|
1091 |
+
yin_scope,
|
1092 |
+
yin_shift_range,
|
1093 |
+
gin_channels=gin_channels)
|
1094 |
+
|
1095 |
+
#self.vq = VQEmbedding(codebook_size, inter_channels - yin_channels)#inter_channels // 2)
|
1096 |
+
self.emb_g = nn.Embedding(self.n_speakers, gin_channels)
|
1097 |
+
|
1098 |
+
self.pitch = Pitch(midi_start=midi_start,
|
1099 |
+
midi_end=midi_end,
|
1100 |
+
octave_range=octave_range)
|
1101 |
+
|
1102 |
+
def crop_scope(
|
1103 |
+
self,
|
1104 |
+
x,
|
1105 |
+
scope_shift=0): # x: list #need to modify for non-scalar shift
|
1106 |
+
return [
|
1107 |
+
i[:, self.yin_start + scope_shift:self.yin_start + self.yin_scope +
|
1108 |
+
scope_shift, :] for i in x
|
1109 |
+
]
|
1110 |
+
|
1111 |
+
def crop_scope_tensor(
|
1112 |
+
self, x,
|
1113 |
+
scope_shift): # x: tensor [B,C,T] #scope_shift: tensor [B]
|
1114 |
+
return torch.stack([
|
1115 |
+
x[i, self.yin_start + scope_shift[i]:self.yin_start +
|
1116 |
+
self.yin_scope + scope_shift[i], :] for i in range(x.shape[0])
|
1117 |
+
],
|
1118 |
+
dim=0)
|
1119 |
+
|
1120 |
+
def yin_dec_infer(self, z_yin, z_mask, sid=None):
|
1121 |
+
if self.n_speakers > 0:
|
1122 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1123 |
+
else:
|
1124 |
+
g = None
|
1125 |
+
return self.yin_dec.infer(z_yin, z_mask, g)
|
1126 |
+
|
1127 |
+
def forward(self,
|
1128 |
+
x,
|
1129 |
+
t,
|
1130 |
+
x_lengths,
|
1131 |
+
y,
|
1132 |
+
y_lengths,
|
1133 |
+
ying,
|
1134 |
+
ying_lengths,
|
1135 |
+
sid=None,
|
1136 |
+
scope_shift=0):
|
1137 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, t, x_lengths)
|
1138 |
+
if self.n_speakers > 0:
|
1139 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1140 |
+
else:
|
1141 |
+
g = None
|
1142 |
+
|
1143 |
+
z_spec, m_spec, logs_spec, spec_mask = self.enc_spec(y, y_lengths, g=g)
|
1144 |
+
|
1145 |
+
#for Q option
|
1146 |
+
#z_spec_q_st, z_spec_q = self.vq.straight_through(z_spec)
|
1147 |
+
#z_spec_q_st = z_spec_q_st * spec_mask
|
1148 |
+
#z_spec_q = z_spec_q * spec_mask
|
1149 |
+
|
1150 |
+
z_yin, m_yin, logs_yin, yin_mask = self.enc_pitch(ying, y_lengths, g=g)
|
1151 |
+
z_yin_crop, logs_yin_crop, m_yin_crop = self.crop_scope(
|
1152 |
+
[z_yin, logs_yin, m_yin], scope_shift)
|
1153 |
+
|
1154 |
+
#yin dec loss
|
1155 |
+
yin_gt_crop, yin_gt_shifted_crop, yin_dec_crop, z_yin_crop_shifted, scope_shift = self.yin_dec(
|
1156 |
+
z_yin, ying, yin_mask, g)
|
1157 |
+
|
1158 |
+
z = torch.cat([z_spec, z_yin], dim=1)
|
1159 |
+
logs_q = torch.cat([logs_spec, logs_yin], dim=1)
|
1160 |
+
m_q = torch.cat([m_spec, m_yin], dim=1)
|
1161 |
+
y_mask = spec_mask
|
1162 |
+
|
1163 |
+
z_p = self.flow(z, y_mask, g=g)
|
1164 |
+
|
1165 |
+
z_dec = torch.cat([z_spec, z_yin_crop], dim=1)
|
1166 |
+
|
1167 |
+
z_dec_shifted = torch.cat([z_spec.detach(), z_yin_crop_shifted], dim=1)
|
1168 |
+
z_dec_ = torch.cat([z_dec, z_dec_shifted], dim=0)
|
1169 |
+
|
1170 |
+
with torch.no_grad():
|
1171 |
+
# negative cross-entropy
|
1172 |
+
s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
|
1173 |
+
# [b, 1, t_s]
|
1174 |
+
neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1],
|
1175 |
+
keepdim=True)
|
1176 |
+
# [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s], z_p: [b,d,t]
|
1177 |
+
#neg_cent2 = torch.matmul(-0.5 * (z_p**2).transpose(1, 2), s_p_sq_r)
|
1178 |
+
neg_cent2 = torch.einsum('bdt, bds -> bts', -0.5 * (z_p**2),
|
1179 |
+
s_p_sq_r)
|
1180 |
+
# [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
1181 |
+
#neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r))
|
1182 |
+
neg_cent3 = torch.einsum('bdt, bds -> bts', z_p, (m_p * s_p_sq_r))
|
1183 |
+
neg_cent4 = torch.sum(-0.5 * (m_p**2) * s_p_sq_r, [1],
|
1184 |
+
keepdim=True) # [b, 1, t_s]
|
1185 |
+
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
|
1186 |
+
|
1187 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(
|
1188 |
+
y_mask, -1)
|
1189 |
+
from monotonic_align import maximum_path
|
1190 |
+
attn = maximum_path(neg_cent,
|
1191 |
+
attn_mask.squeeze(1)).unsqueeze(1).detach()
|
1192 |
+
|
1193 |
+
w = attn.sum(2)
|
1194 |
+
if self.use_sdp:
|
1195 |
+
l_length = self.dp(x, x_mask, w, g=g)
|
1196 |
+
l_length = l_length / torch.sum(x_mask)
|
1197 |
+
else:
|
1198 |
+
logw_ = torch.log(w + 1e-6) * x_mask
|
1199 |
+
logw = self.dp(x, x_mask, g=g)
|
1200 |
+
l_length = torch.sum(
|
1201 |
+
(logw - logw_)**2, [1, 2]) / torch.sum(x_mask) # for averaging
|
1202 |
+
|
1203 |
+
# expand prior
|
1204 |
+
m_p = torch.einsum('bctn, bdn -> bdt', attn, m_p)
|
1205 |
+
logs_p = torch.einsum('bctn, bdn -> bdt', attn, logs_p)
|
1206 |
+
|
1207 |
+
#z_slice, ids_slice = commons.rand_slice_segments(z_dec, y_lengths, self.segment_size)
|
1208 |
+
#o = self.dec(z_slice, g=g)
|
1209 |
+
z_slice, ids_slice = commons.rand_slice_segments_for_cat(
|
1210 |
+
z_dec_, torch.cat([y_lengths, y_lengths], dim=0),
|
1211 |
+
self.segment_size)
|
1212 |
+
o_ = self.dec.hier_forward(z_slice, g=torch.cat([g, g], dim=0))
|
1213 |
+
o = [torch.chunk(o_hier, 2, dim=0)[0] for o_hier in o_]
|
1214 |
+
|
1215 |
+
o_pad = F.pad(o_[-1], (768, 768 + (-o_[-1].shape[-1]) % 256 + 256 *
|
1216 |
+
(o_[-1].shape[-1] % 256 == 0)),
|
1217 |
+
mode='constant').squeeze(1)
|
1218 |
+
yin_hat = self.pitch.yingram(o_pad)
|
1219 |
+
yin_hat_crop = self.crop_scope([yin_hat])[0]
|
1220 |
+
yin_hat_shifted = self.crop_scope_tensor(
|
1221 |
+
torch.chunk(yin_hat, 2, dim=0)[0], scope_shift)
|
1222 |
+
return o, l_length, attn, ids_slice, x_mask, y_mask, o_, \
|
1223 |
+
(z, z_p, m_p, logs_p, m_q, logs_q), \
|
1224 |
+
(z_dec_), \
|
1225 |
+
(z_spec, m_spec, logs_spec, spec_mask, z_yin, m_yin, logs_yin, yin_mask), \
|
1226 |
+
(yin_gt_crop, yin_gt_shifted_crop, yin_dec_crop, yin_hat_crop, scope_shift, yin_hat_shifted)
|
1227 |
+
|
1228 |
+
def infer(self,
|
1229 |
+
x,
|
1230 |
+
t,
|
1231 |
+
x_lengths,
|
1232 |
+
sid=None,
|
1233 |
+
noise_scale=1,
|
1234 |
+
length_scale=1,
|
1235 |
+
noise_scale_w=1.,
|
1236 |
+
max_len=None,
|
1237 |
+
scope_shift=0): #need to fix #vector scope shift needed
|
1238 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, t, x_lengths)
|
1239 |
+
if self.n_speakers > 0:
|
1240 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1241 |
+
else:
|
1242 |
+
g = None
|
1243 |
+
|
1244 |
+
if self.use_sdp:
|
1245 |
+
logw = self.dp(x,
|
1246 |
+
x_mask,
|
1247 |
+
g=g,
|
1248 |
+
reverse=True,
|
1249 |
+
noise_scale=noise_scale_w)
|
1250 |
+
else:
|
1251 |
+
logw = self.dp(x, x_mask, g=g)
|
1252 |
+
w = torch.exp(logw) * x_mask * length_scale
|
1253 |
+
w_ceil = torch.ceil(w)
|
1254 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
1255 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None),
|
1256 |
+
1).to(x_mask.dtype)
|
1257 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
1258 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
1259 |
+
|
1260 |
+
m_p = torch.einsum('bctn, bdn -> bdt', attn, m_p)
|
1261 |
+
logs_p = torch.einsum('bctn, bdn -> bdt', attn, logs_p)
|
1262 |
+
|
1263 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
1264 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
1265 |
+
z_spec, z_yin = torch.split(z,
|
1266 |
+
self.inter_channels - self.yin_channels,
|
1267 |
+
dim=1)
|
1268 |
+
z_yin_crop = self.crop_scope([z_yin], scope_shift)[0]
|
1269 |
+
z_crop = torch.cat([z_spec, z_yin_crop], dim=1)
|
1270 |
+
o = self.dec((z_crop * y_mask)[:, :, :max_len], g=g)
|
1271 |
+
return o, attn, y_mask, (z_crop, z, z_p, m_p, logs_p)
|
1272 |
+
|
1273 |
+
def infer_pre_decoder(self,
|
1274 |
+
x,
|
1275 |
+
t,
|
1276 |
+
x_lengths,
|
1277 |
+
sid=None,
|
1278 |
+
noise_scale=1.,
|
1279 |
+
length_scale=1.,
|
1280 |
+
noise_scale_w=1.,
|
1281 |
+
max_len=None,
|
1282 |
+
scope_shift=0):
|
1283 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, t, x_lengths)
|
1284 |
+
if self.n_speakers > 0:
|
1285 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1286 |
+
else:
|
1287 |
+
g = None
|
1288 |
+
|
1289 |
+
if self.use_sdp:
|
1290 |
+
logw = self.dp(x,
|
1291 |
+
x_mask,
|
1292 |
+
g=g,
|
1293 |
+
reverse=True,
|
1294 |
+
noise_scale=noise_scale_w)
|
1295 |
+
else:
|
1296 |
+
logw = self.dp(x, x_mask, g=g)
|
1297 |
+
w = torch.exp(logw) * x_mask * length_scale
|
1298 |
+
w_ceil = torch.ceil(w)
|
1299 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
1300 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None),
|
1301 |
+
1).to(x_mask.dtype)
|
1302 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
1303 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
1304 |
+
|
1305 |
+
m_p = torch.einsum('bctn, bdn -> bdt', attn, m_p)
|
1306 |
+
logs_p = torch.einsum('bctn, bdn -> bdt', attn, logs_p)
|
1307 |
+
|
1308 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
1309 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
1310 |
+
z_spec, z_yin = torch.split(z,
|
1311 |
+
self.inter_channels - self.yin_channels,
|
1312 |
+
dim=1)
|
1313 |
+
z_yin_crop = self.crop_scope([z_yin], scope_shift)[0]
|
1314 |
+
z_crop = torch.cat([z_spec, z_yin_crop], dim=1)
|
1315 |
+
decoder_inputs = z_crop * y_mask
|
1316 |
+
return decoder_inputs, attn, y_mask, (z_crop, z, z_p, m_p, logs_p)
|
1317 |
+
|
1318 |
+
def infer_pre_lr(
|
1319 |
+
self,
|
1320 |
+
x,
|
1321 |
+
t,
|
1322 |
+
x_lengths,
|
1323 |
+
sid=None,
|
1324 |
+
length_scale=1,
|
1325 |
+
noise_scale_w=1.,
|
1326 |
+
):
|
1327 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, t, x_lengths)
|
1328 |
+
if self.n_speakers > 0:
|
1329 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1330 |
+
else:
|
1331 |
+
g = None
|
1332 |
+
|
1333 |
+
if self.use_sdp:
|
1334 |
+
logw = self.dp(x,
|
1335 |
+
x_mask,
|
1336 |
+
g=g,
|
1337 |
+
reverse=True,
|
1338 |
+
noise_scale=noise_scale_w)
|
1339 |
+
else:
|
1340 |
+
logw = self.dp(x, x_mask, g=g)
|
1341 |
+
w = torch.exp(logw) * x_mask * length_scale
|
1342 |
+
w_ceil = torch.ceil(w)
|
1343 |
+
return w_ceil, x, m_p, logs_p, x_mask, g
|
1344 |
+
|
1345 |
+
def infer_lr(self, w_ceil, x, m_p, logs_p, x_mask):
|
1346 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
1347 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None),
|
1348 |
+
1).to(x_mask.dtype)
|
1349 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
1350 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
1351 |
+
|
1352 |
+
m_p = torch.einsum('bctn, bdn -> bdt', attn, m_p)
|
1353 |
+
logs_p = torch.einsum('bctn, bdn -> bdt', attn, logs_p)
|
1354 |
+
return m_p, logs_p, y_mask
|
1355 |
+
|
1356 |
+
def infer_post_lr_pre_decoder(self,
|
1357 |
+
m_p,
|
1358 |
+
logs_p,
|
1359 |
+
g,
|
1360 |
+
y_mask,
|
1361 |
+
noise_scale=1,
|
1362 |
+
scope_shift=0):
|
1363 |
+
|
1364 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
1365 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
1366 |
+
z_spec, z_yin = torch.split(z,
|
1367 |
+
self.inter_channels - self.yin_channels,
|
1368 |
+
dim=1)
|
1369 |
+
|
1370 |
+
z_yin_crop = self.crop_scope([z_yin], scope_shift)[0]
|
1371 |
+
z_crop = torch.cat([z_spec, z_yin_crop], dim=1)
|
1372 |
+
decoder_inputs = z_crop * y_mask
|
1373 |
+
|
1374 |
+
return decoder_inputs, y_mask, (z_crop, z, z_p, m_p, logs_p)
|
1375 |
+
|
1376 |
+
def infer_decode_chunk(self, decoder_inputs, sid=None):
|
1377 |
+
if self.n_speakers > 0:
|
1378 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
1379 |
+
else:
|
1380 |
+
g = None
|
1381 |
+
return self.dec(decoder_inputs, g=g)
|
1382 |
+
|
1383 |
+
|
modules.py
ADDED
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import Conv1d
|
6 |
+
from torch.nn import functional as F
|
7 |
+
from torch.nn.utils import weight_norm, remove_weight_norm
|
8 |
+
|
9 |
+
import commons
|
10 |
+
from commons import init_weights, get_padding
|
11 |
+
from transforms import piecewise_rational_quadratic_transform
|
12 |
+
|
13 |
+
|
14 |
+
LRELU_SLOPE = 0.1
|
15 |
+
|
16 |
+
|
17 |
+
class LayerNorm(nn.Module):
|
18 |
+
def __init__(self, channels, eps=1e-5):
|
19 |
+
super().__init__()
|
20 |
+
self.channels = channels
|
21 |
+
self.eps = eps
|
22 |
+
|
23 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
24 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
25 |
+
|
26 |
+
def forward(self, x):
|
27 |
+
x = x.transpose(1, -1)
|
28 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
29 |
+
return x.transpose(1, -1)
|
30 |
+
|
31 |
+
|
32 |
+
class ConvReluNorm(nn.Module):
|
33 |
+
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
|
34 |
+
super().__init__()
|
35 |
+
self.in_channels = in_channels
|
36 |
+
self.hidden_channels = hidden_channels
|
37 |
+
self.out_channels = out_channels
|
38 |
+
self.kernel_size = kernel_size
|
39 |
+
self.n_layers = n_layers
|
40 |
+
self.p_dropout = p_dropout
|
41 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
42 |
+
|
43 |
+
self.conv_layers = nn.ModuleList()
|
44 |
+
self.norm_layers = nn.ModuleList()
|
45 |
+
self.conv_layers.append(
|
46 |
+
nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2)
|
47 |
+
)
|
48 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
49 |
+
self.relu_drop = nn.Sequential(
|
50 |
+
nn.ReLU(),
|
51 |
+
nn.Dropout(p_dropout))
|
52 |
+
for _ in range(n_layers-1):
|
53 |
+
self.conv_layers.append(nn.Conv1d(
|
54 |
+
hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2)
|
55 |
+
)
|
56 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
57 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
58 |
+
self.proj.weight.data.zero_()
|
59 |
+
self.proj.bias.data.zero_()
|
60 |
+
|
61 |
+
def forward(self, x, x_mask):
|
62 |
+
x_org = x
|
63 |
+
for i in range(self.n_layers):
|
64 |
+
x = self.conv_layers[i](x * x_mask)
|
65 |
+
x = self.norm_layers[i](x)
|
66 |
+
x = self.relu_drop(x)
|
67 |
+
x = x_org + self.proj(x)
|
68 |
+
return x * x_mask
|
69 |
+
|
70 |
+
|
71 |
+
class DDSConv(nn.Module):
|
72 |
+
"""Dialted and Depth-Separable Convolution"""
|
73 |
+
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
|
74 |
+
super().__init__()
|
75 |
+
self.channels = channels
|
76 |
+
self.kernel_size = kernel_size
|
77 |
+
self.n_layers = n_layers
|
78 |
+
self.p_dropout = p_dropout
|
79 |
+
|
80 |
+
self.drop = nn.Dropout(p_dropout)
|
81 |
+
self.convs_sep = nn.ModuleList()
|
82 |
+
self.convs_1x1 = nn.ModuleList()
|
83 |
+
self.norms_1 = nn.ModuleList()
|
84 |
+
self.norms_2 = nn.ModuleList()
|
85 |
+
for i in range(n_layers):
|
86 |
+
dilation = kernel_size ** i
|
87 |
+
padding = (kernel_size * dilation - dilation) // 2
|
88 |
+
self.convs_sep.append(
|
89 |
+
nn.Conv1d(
|
90 |
+
channels,
|
91 |
+
channels,
|
92 |
+
kernel_size,
|
93 |
+
groups=channels,
|
94 |
+
dilation=dilation,
|
95 |
+
padding=padding
|
96 |
+
)
|
97 |
+
)
|
98 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
99 |
+
self.norms_1.append(LayerNorm(channels))
|
100 |
+
self.norms_2.append(LayerNorm(channels))
|
101 |
+
|
102 |
+
def forward(self, x, x_mask, g=None):
|
103 |
+
if g is not None:
|
104 |
+
x = x + g
|
105 |
+
for i in range(self.n_layers):
|
106 |
+
y = self.convs_sep[i](x * x_mask)
|
107 |
+
y = self.norms_1[i](y)
|
108 |
+
y = F.gelu(y)
|
109 |
+
y = self.convs_1x1[i](y)
|
110 |
+
y = self.norms_2[i](y)
|
111 |
+
y = F.gelu(y)
|
112 |
+
y = self.drop(y)
|
113 |
+
x = x + y
|
114 |
+
return x * x_mask
|
115 |
+
|
116 |
+
|
117 |
+
class WN(torch.nn.Module):
|
118 |
+
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
|
119 |
+
super(WN, self).__init__()
|
120 |
+
assert(kernel_size % 2 == 1)
|
121 |
+
self.hidden_channels = hidden_channels
|
122 |
+
self.kernel_size = kernel_size,
|
123 |
+
self.dilation_rate = dilation_rate
|
124 |
+
self.n_layers = n_layers
|
125 |
+
self.gin_channels = gin_channels
|
126 |
+
self.p_dropout = p_dropout
|
127 |
+
|
128 |
+
self.in_layers = torch.nn.ModuleList()
|
129 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
130 |
+
self.drop = nn.Dropout(p_dropout)
|
131 |
+
|
132 |
+
if gin_channels != 0:
|
133 |
+
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
|
134 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
|
135 |
+
|
136 |
+
for i in range(n_layers):
|
137 |
+
dilation = dilation_rate ** i
|
138 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
139 |
+
in_layer = torch.nn.Conv1d(
|
140 |
+
hidden_channels,
|
141 |
+
2*hidden_channels,
|
142 |
+
kernel_size,
|
143 |
+
dilation=dilation,
|
144 |
+
padding=padding
|
145 |
+
)
|
146 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
|
147 |
+
self.in_layers.append(in_layer)
|
148 |
+
|
149 |
+
# last one is not necessary
|
150 |
+
if i < n_layers - 1:
|
151 |
+
res_skip_channels = 2 * hidden_channels
|
152 |
+
else:
|
153 |
+
res_skip_channels = hidden_channels
|
154 |
+
|
155 |
+
res_skip_layer = torch.nn.Conv1d(
|
156 |
+
hidden_channels, res_skip_channels, 1
|
157 |
+
)
|
158 |
+
res_skip_layer = torch.nn.utils.weight_norm(
|
159 |
+
res_skip_layer, name='weight'
|
160 |
+
)
|
161 |
+
self.res_skip_layers.append(res_skip_layer)
|
162 |
+
|
163 |
+
def forward(self, x, x_mask, g=None, **kwargs):
|
164 |
+
output = torch.zeros_like(x)
|
165 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
166 |
+
|
167 |
+
if g is not None:
|
168 |
+
g = self.cond_layer(g)
|
169 |
+
|
170 |
+
for i in range(self.n_layers):
|
171 |
+
x_in = self.in_layers[i](x)
|
172 |
+
if g is not None:
|
173 |
+
cond_offset = i * 2 * self.hidden_channels
|
174 |
+
g_l = g[:, cond_offset:cond_offset+2*self.hidden_channels, :]
|
175 |
+
else:
|
176 |
+
g_l = torch.zeros_like(x_in)
|
177 |
+
|
178 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(
|
179 |
+
x_in,
|
180 |
+
g_l,
|
181 |
+
n_channels_tensor
|
182 |
+
)
|
183 |
+
acts = self.drop(acts)
|
184 |
+
|
185 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
186 |
+
if i < self.n_layers - 1:
|
187 |
+
res_acts = res_skip_acts[:, :self.hidden_channels, :]
|
188 |
+
x = (x + res_acts) * x_mask
|
189 |
+
output = output + res_skip_acts[:, self.hidden_channels:, :]
|
190 |
+
else:
|
191 |
+
output = output + res_skip_acts
|
192 |
+
return output * x_mask
|
193 |
+
|
194 |
+
def remove_weight_norm(self):
|
195 |
+
if self.gin_channels != 0:
|
196 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
197 |
+
for l in self.in_layers:
|
198 |
+
torch.nn.utils.remove_weight_norm(l)
|
199 |
+
for l in self.res_skip_layers:
|
200 |
+
torch.nn.utils.remove_weight_norm(l)
|
201 |
+
|
202 |
+
|
203 |
+
class ResBlock1(torch.nn.Module):
|
204 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
205 |
+
super(ResBlock1, self).__init__()
|
206 |
+
self.convs1 = nn.ModuleList([
|
207 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
208 |
+
padding=get_padding(kernel_size, dilation[0]))),
|
209 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
210 |
+
padding=get_padding(kernel_size, dilation[1]))),
|
211 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
212 |
+
padding=get_padding(kernel_size, dilation[2])))
|
213 |
+
])
|
214 |
+
self.convs1.apply(init_weights)
|
215 |
+
|
216 |
+
self.convs2 = nn.ModuleList([
|
217 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
218 |
+
padding=get_padding(kernel_size, 1))),
|
219 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
220 |
+
padding=get_padding(kernel_size, 1))),
|
221 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
222 |
+
padding=get_padding(kernel_size, 1)))
|
223 |
+
])
|
224 |
+
self.convs2.apply(init_weights)
|
225 |
+
|
226 |
+
def forward(self, x, x_mask=None):
|
227 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
228 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
229 |
+
if x_mask is not None:
|
230 |
+
xt = xt * x_mask
|
231 |
+
xt = c1(xt)
|
232 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
233 |
+
if x_mask is not None:
|
234 |
+
xt = xt * x_mask
|
235 |
+
xt = c2(xt)
|
236 |
+
x = xt + x
|
237 |
+
if x_mask is not None:
|
238 |
+
x = x * x_mask
|
239 |
+
return x
|
240 |
+
|
241 |
+
def remove_weight_norm(self):
|
242 |
+
for l in self.convs1:
|
243 |
+
remove_weight_norm(l)
|
244 |
+
for l in self.convs2:
|
245 |
+
remove_weight_norm(l)
|
246 |
+
|
247 |
+
|
248 |
+
class ResBlock2(torch.nn.Module):
|
249 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
250 |
+
super(ResBlock2, self).__init__()
|
251 |
+
self.convs = nn.ModuleList([
|
252 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
253 |
+
padding=get_padding(kernel_size, dilation[0]))),
|
254 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
255 |
+
padding=get_padding(kernel_size, dilation[1])))
|
256 |
+
])
|
257 |
+
self.convs.apply(init_weights)
|
258 |
+
|
259 |
+
def forward(self, x, x_mask=None):
|
260 |
+
for c in self.convs:
|
261 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
262 |
+
if x_mask is not None:
|
263 |
+
xt = xt * x_mask
|
264 |
+
xt = c(xt)
|
265 |
+
x = xt + x
|
266 |
+
if x_mask is not None:
|
267 |
+
x = x * x_mask
|
268 |
+
return x
|
269 |
+
|
270 |
+
def remove_weight_norm(self):
|
271 |
+
for l in self.convs:
|
272 |
+
remove_weight_norm(l)
|
273 |
+
|
274 |
+
|
275 |
+
class Log(nn.Module):
|
276 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
277 |
+
if not reverse:
|
278 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
279 |
+
logdet = torch.sum(-y, [1, 2])
|
280 |
+
return y, logdet
|
281 |
+
else:
|
282 |
+
x = torch.exp(x) * x_mask
|
283 |
+
return x
|
284 |
+
|
285 |
+
|
286 |
+
class Flip(nn.Module):
|
287 |
+
def forward(self, x, *args, reverse=False, **kwargs):
|
288 |
+
x = torch.flip(x, [1])
|
289 |
+
if not reverse:
|
290 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
291 |
+
return x, logdet
|
292 |
+
else:
|
293 |
+
return x
|
294 |
+
|
295 |
+
|
296 |
+
class ElementwiseAffine(nn.Module):
|
297 |
+
def __init__(self, channels):
|
298 |
+
super().__init__()
|
299 |
+
self.channels = channels
|
300 |
+
self.m = nn.Parameter(torch.zeros(channels, 1))
|
301 |
+
self.logs = nn.Parameter(torch.zeros(channels, 1))
|
302 |
+
|
303 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
304 |
+
if not reverse:
|
305 |
+
y = self.m + torch.exp(self.logs) * x
|
306 |
+
y = y * x_mask
|
307 |
+
logdet = torch.sum(self.logs * x_mask, [1, 2])
|
308 |
+
return y, logdet
|
309 |
+
else:
|
310 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
311 |
+
return x
|
312 |
+
|
313 |
+
|
314 |
+
class ResidualCouplingLayer(nn.Module):
|
315 |
+
def __init__(
|
316 |
+
self,
|
317 |
+
channels,
|
318 |
+
hidden_channels,
|
319 |
+
kernel_size,
|
320 |
+
dilation_rate,
|
321 |
+
n_layers,
|
322 |
+
p_dropout=0,
|
323 |
+
gin_channels=0,
|
324 |
+
mean_only=False
|
325 |
+
):
|
326 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
327 |
+
super().__init__()
|
328 |
+
self.channels = channels
|
329 |
+
self.hidden_channels = hidden_channels
|
330 |
+
self.kernel_size = kernel_size
|
331 |
+
self.dilation_rate = dilation_rate
|
332 |
+
self.n_layers = n_layers
|
333 |
+
self.half_channels = channels // 2
|
334 |
+
self.mean_only = mean_only
|
335 |
+
|
336 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
337 |
+
self.enc = WN(
|
338 |
+
hidden_channels,
|
339 |
+
kernel_size,
|
340 |
+
dilation_rate,
|
341 |
+
n_layers,
|
342 |
+
p_dropout=p_dropout,
|
343 |
+
gin_channels=gin_channels
|
344 |
+
)
|
345 |
+
self.post = nn.Conv1d(
|
346 |
+
hidden_channels, self.half_channels * (2 - mean_only), 1
|
347 |
+
)
|
348 |
+
self.post.weight.data.zero_()
|
349 |
+
self.post.bias.data.zero_()
|
350 |
+
|
351 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
352 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
353 |
+
h = self.pre(x0) * x_mask
|
354 |
+
h = self.enc(h, x_mask, g=g)
|
355 |
+
stats = self.post(h) * x_mask
|
356 |
+
if not self.mean_only:
|
357 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
358 |
+
else:
|
359 |
+
m = stats
|
360 |
+
logs = torch.zeros_like(m)
|
361 |
+
|
362 |
+
if not reverse:
|
363 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
364 |
+
x = torch.cat([x0, x1], 1)
|
365 |
+
logdet = torch.sum(logs, [1, 2])
|
366 |
+
return x, logdet
|
367 |
+
else:
|
368 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
369 |
+
x = torch.cat([x0, x1], 1)
|
370 |
+
return x
|
371 |
+
|
372 |
+
|
373 |
+
class ConvFlow(nn.Module):
|
374 |
+
def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
|
375 |
+
super().__init__()
|
376 |
+
self.in_channels = in_channels
|
377 |
+
self.filter_channels = filter_channels
|
378 |
+
self.kernel_size = kernel_size
|
379 |
+
self.n_layers = n_layers
|
380 |
+
self.num_bins = num_bins
|
381 |
+
self.tail_bound = tail_bound
|
382 |
+
self.half_channels = in_channels // 2
|
383 |
+
|
384 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
385 |
+
self.convs = DDSConv(
|
386 |
+
filter_channels, kernel_size, n_layers, p_dropout=0.
|
387 |
+
)
|
388 |
+
self.proj = nn.Conv1d(
|
389 |
+
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
|
390 |
+
)
|
391 |
+
self.proj.weight.data.zero_()
|
392 |
+
self.proj.bias.data.zero_()
|
393 |
+
|
394 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
395 |
+
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
396 |
+
h = self.pre(x0)
|
397 |
+
h = self.convs(h, x_mask, g=g)
|
398 |
+
h = self.proj(h) * x_mask
|
399 |
+
|
400 |
+
b, c, t = x0.shape
|
401 |
+
# [b, cx?, t] -> [b, c, t, ?]
|
402 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2)
|
403 |
+
|
404 |
+
unnormalized_widths = h[..., :self.num_bins] / \
|
405 |
+
math.sqrt(self.filter_channels)
|
406 |
+
unnormalized_heights = h[..., self.num_bins:2 * self.num_bins] / \
|
407 |
+
math.sqrt(self.filter_channels)
|
408 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins:]
|
409 |
+
|
410 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
411 |
+
x1,
|
412 |
+
unnormalized_widths,
|
413 |
+
unnormalized_heights,
|
414 |
+
unnormalized_derivatives,
|
415 |
+
inverse=reverse,
|
416 |
+
tails='linear',
|
417 |
+
tail_bound=self.tail_bound
|
418 |
+
)
|
419 |
+
|
420 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
421 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
422 |
+
if not reverse:
|
423 |
+
return x, logdet
|
424 |
+
else:
|
425 |
+
return x
|
pqmf.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
|
3 |
+
# Copyright 2020 Tomoki Hayashi
|
4 |
+
# MIT License (https://opensource.org/licenses/MIT)
|
5 |
+
|
6 |
+
"""Pseudo QMF modules."""
|
7 |
+
'''
|
8 |
+
Copied from https://github.com/kan-bayashi/ParallelWaveGAN/blob/master/parallel_wavegan/layers/pqmf.py
|
9 |
+
'''
|
10 |
+
|
11 |
+
import numpy as np
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
|
15 |
+
from scipy.signal import kaiser
|
16 |
+
|
17 |
+
|
18 |
+
def design_prototype_filter(taps=62, cutoff_ratio=0.142, beta=9.0):
|
19 |
+
"""Design prototype filter for PQMF.
|
20 |
+
This method is based on `A Kaiser window approach for the design of prototype
|
21 |
+
filters of cosine modulated filterbanks`_.
|
22 |
+
Args:
|
23 |
+
taps (int): The number of filter taps.
|
24 |
+
cutoff_ratio (float): Cut-off frequency ratio.
|
25 |
+
beta (float): Beta coefficient for kaiser window.
|
26 |
+
Returns:
|
27 |
+
ndarray: Impluse response of prototype filter (taps + 1,).
|
28 |
+
.. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`:
|
29 |
+
https://ieeexplore.ieee.org/abstract/document/681427
|
30 |
+
"""
|
31 |
+
# check the arguments are valid
|
32 |
+
assert taps % 2 == 0, "The number of taps mush be even number."
|
33 |
+
assert 0.0 < cutoff_ratio < 1.0, "Cutoff ratio must be > 0.0 and < 1.0."
|
34 |
+
|
35 |
+
# make initial filter
|
36 |
+
omega_c = np.pi * cutoff_ratio
|
37 |
+
with np.errstate(invalid="ignore"):
|
38 |
+
h_i = np.sin(omega_c * (np.arange(taps + 1) - 0.5 * taps)) / (
|
39 |
+
np.pi * (np.arange(taps + 1) - 0.5 * taps)
|
40 |
+
)
|
41 |
+
h_i[taps // 2] = np.cos(0) * cutoff_ratio # fix nan due to indeterminate form
|
42 |
+
|
43 |
+
# apply kaiser window
|
44 |
+
w = kaiser(taps + 1, beta)
|
45 |
+
h = h_i * w
|
46 |
+
|
47 |
+
return h
|
48 |
+
|
49 |
+
|
50 |
+
class PQMF(torch.nn.Module):
|
51 |
+
"""PQMF module.
|
52 |
+
This module is based on `Near-perfect-reconstruction pseudo-QMF banks`_.
|
53 |
+
.. _`Near-perfect-reconstruction pseudo-QMF banks`:
|
54 |
+
https://ieeexplore.ieee.org/document/258122
|
55 |
+
"""
|
56 |
+
|
57 |
+
def __init__(self, subbands=4, taps=62, cutoff_ratio=0.142, beta=9.0):
|
58 |
+
"""Initilize PQMF module.
|
59 |
+
The cutoff_ratio and beta parameters are optimized for #subbands = 4.
|
60 |
+
See dicussion in https://github.com/kan-bayashi/ParallelWaveGAN/issues/195.
|
61 |
+
Args:
|
62 |
+
subbands (int): The number of subbands.
|
63 |
+
taps (int): The number of filter taps.
|
64 |
+
cutoff_ratio (float): Cut-off frequency ratio.
|
65 |
+
beta (float): Beta coefficient for kaiser window.
|
66 |
+
"""
|
67 |
+
super(PQMF, self).__init__()
|
68 |
+
|
69 |
+
# build analysis & synthesis filter coefficients
|
70 |
+
h_proto = design_prototype_filter(taps, cutoff_ratio, beta)
|
71 |
+
h_analysis = np.zeros((subbands, len(h_proto)))
|
72 |
+
h_synthesis = np.zeros((subbands, len(h_proto)))
|
73 |
+
for k in range(subbands):
|
74 |
+
h_analysis[k] = (
|
75 |
+
2
|
76 |
+
* h_proto
|
77 |
+
* np.cos(
|
78 |
+
(2 * k + 1)
|
79 |
+
* (np.pi / (2 * subbands))
|
80 |
+
* (np.arange(taps + 1) - (taps / 2))
|
81 |
+
+ (-1) ** k * np.pi / 4
|
82 |
+
)
|
83 |
+
)
|
84 |
+
h_synthesis[k] = (
|
85 |
+
2
|
86 |
+
* h_proto
|
87 |
+
* np.cos(
|
88 |
+
(2 * k + 1)
|
89 |
+
* (np.pi / (2 * subbands))
|
90 |
+
* (np.arange(taps + 1) - (taps / 2))
|
91 |
+
- (-1) ** k * np.pi / 4
|
92 |
+
)
|
93 |
+
)
|
94 |
+
|
95 |
+
# convert to tensor
|
96 |
+
analysis_filter = torch.Tensor(h_analysis).float().unsqueeze(1)
|
97 |
+
synthesis_filter = torch.Tensor(h_synthesis).float().unsqueeze(0)
|
98 |
+
|
99 |
+
# register coefficients as beffer
|
100 |
+
self.register_buffer("analysis_filter", analysis_filter)
|
101 |
+
self.register_buffer("synthesis_filter", synthesis_filter)
|
102 |
+
|
103 |
+
# filter for downsampling & upsampling
|
104 |
+
updown_filter = torch.zeros((subbands, subbands, subbands)).float()
|
105 |
+
for k in range(subbands):
|
106 |
+
updown_filter[k, k, 0] = 1.0
|
107 |
+
self.register_buffer("updown_filter", updown_filter)
|
108 |
+
self.subbands = subbands
|
109 |
+
|
110 |
+
# keep padding info
|
111 |
+
self.pad_fn = torch.nn.ConstantPad1d(taps // 2, 0.0)
|
112 |
+
|
113 |
+
def analysis(self, x):
|
114 |
+
"""Analysis with PQMF.
|
115 |
+
Args:
|
116 |
+
x (Tensor): Input tensor (B, 1, T).
|
117 |
+
Returns:
|
118 |
+
Tensor: Output tensor (B, subbands, T // subbands).
|
119 |
+
"""
|
120 |
+
x = F.conv1d(self.pad_fn(x), self.analysis_filter)
|
121 |
+
return F.conv1d(x, self.updown_filter, stride=self.subbands)
|
122 |
+
|
123 |
+
def synthesis(self, x):
|
124 |
+
"""Synthesis with PQMF.
|
125 |
+
Args:
|
126 |
+
x (Tensor): Input tensor (B, subbands, T // subbands).
|
127 |
+
Returns:
|
128 |
+
Tensor: Output tensor (B, 1, T).
|
129 |
+
"""
|
130 |
+
# NOTE(kan-bayashi): Power will be dreased so here multipy by # subbands.
|
131 |
+
# Not sure this is the correct way, it is better to check again.
|
132 |
+
# TODO(kan-bayashi): Understand the reconstruction procedure
|
133 |
+
x = F.conv_transpose1d(
|
134 |
+
x, self.updown_filter * self.subbands, stride=self.subbands
|
135 |
+
)
|
136 |
+
return F.conv1d(self.pad_fn(x), self.synthesis_filter)
|
text/__init__.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" from https://github.com/keithito/tacotron """
|
2 |
+
import re
|
3 |
+
from unicodedata import normalize
|
4 |
+
|
5 |
+
from text.cleaners import collapse_whitespace
|
6 |
+
from text.symbols import lang_to_dict, lang_to_dict_inverse
|
7 |
+
|
8 |
+
|
9 |
+
def text_to_sequence(raw_text, lang):
|
10 |
+
'''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
|
11 |
+
Args:
|
12 |
+
text: string to convert to a sequence
|
13 |
+
lang: language of the input text
|
14 |
+
Returns:
|
15 |
+
List of integers corresponding to the symbols in the text
|
16 |
+
'''
|
17 |
+
|
18 |
+
_symbol_to_id = lang_to_dict(lang)
|
19 |
+
text = collapse_whitespace(raw_text)
|
20 |
+
|
21 |
+
if lang == 'ko_KR':
|
22 |
+
text = normalize('NFKD', text)
|
23 |
+
sequence = [_symbol_to_id[symbol] for symbol in text]
|
24 |
+
tone = [0 for i in sequence]
|
25 |
+
|
26 |
+
elif lang == 'en_US':
|
27 |
+
_curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)')
|
28 |
+
sequence = []
|
29 |
+
|
30 |
+
while len(text):
|
31 |
+
m = _curly_re.match(text)
|
32 |
+
|
33 |
+
if m is not None:
|
34 |
+
ar = m.group(1)
|
35 |
+
sequence += [_symbol_to_id[symbol] for symbol in ar]
|
36 |
+
ar = m.group(2)
|
37 |
+
sequence += [_symbol_to_id[symbol] for symbol in ar.split()]
|
38 |
+
text = m.group(3)
|
39 |
+
else:
|
40 |
+
sequence += [_symbol_to_id[symbol] for symbol in text]
|
41 |
+
break
|
42 |
+
|
43 |
+
tone = [0 for i in sequence]
|
44 |
+
|
45 |
+
else:
|
46 |
+
raise RuntimeError('Wrong type of lang')
|
47 |
+
|
48 |
+
assert len(sequence) == len(tone)
|
49 |
+
return sequence, tone
|
50 |
+
|
51 |
+
|
52 |
+
def sequence_to_text(sequence, lang):
|
53 |
+
'''Converts a sequence of IDs back to a string'''
|
54 |
+
_id_to_symbol = lang_to_dict_inverse(lang)
|
55 |
+
result = ''
|
56 |
+
for symbol_id in sequence:
|
57 |
+
s = _id_to_symbol[symbol_id]
|
58 |
+
result += s
|
59 |
+
return result
|
60 |
+
|
61 |
+
|
62 |
+
def _clean_text(text, cleaner_names):
|
63 |
+
for name in cleaner_names:
|
64 |
+
cleaner = getattr(cleaners, name)
|
65 |
+
if not cleaner:
|
66 |
+
raise Exception('Unknown cleaner: %s' % name)
|
67 |
+
text = cleaner(text)
|
68 |
+
return text
|
text/cleaners.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" from https://github.com/keithito/tacotron """
|
2 |
+
|
3 |
+
'''
|
4 |
+
Cleaners are transformations that run over the input text at both training and eval time.
|
5 |
+
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
|
6 |
+
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
|
7 |
+
1. "english_cleaners" for English text
|
8 |
+
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
|
9 |
+
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
|
10 |
+
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
|
11 |
+
the symbols in symbols.py to match your data).
|
12 |
+
'''
|
13 |
+
|
14 |
+
import re
|
15 |
+
from unidecode import unidecode
|
16 |
+
from unicodedata import normalize
|
17 |
+
|
18 |
+
from .numbers import normalize_numbers
|
19 |
+
|
20 |
+
|
21 |
+
# Regular expression matching whitespace:
|
22 |
+
_whitespace_re = re.compile(r'\s+')
|
23 |
+
|
24 |
+
# List of (regular expression, replacement) pairs for abbreviations:
|
25 |
+
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
|
26 |
+
('mrs', 'misess'),
|
27 |
+
('mr', 'mister'),
|
28 |
+
('dr', 'doctor'),
|
29 |
+
('st', 'saint'),
|
30 |
+
('co', 'company'),
|
31 |
+
('jr', 'junior'),
|
32 |
+
('maj', 'major'),
|
33 |
+
('gen', 'general'),
|
34 |
+
('drs', 'doctors'),
|
35 |
+
('rev', 'reverend'),
|
36 |
+
('lt', 'lieutenant'),
|
37 |
+
('hon', 'honorable'),
|
38 |
+
('sgt', 'sergeant'),
|
39 |
+
('capt', 'captain'),
|
40 |
+
('esq', 'esquire'),
|
41 |
+
('ltd', 'limited'),
|
42 |
+
('col', 'colonel'),
|
43 |
+
('ft', 'fort'),
|
44 |
+
]]
|
45 |
+
|
46 |
+
_cht_norm = [(re.compile(r'[%s]' % x[0]), x[1]) for x in [
|
47 |
+
('。.;', '.'),
|
48 |
+
(',、', ', '),
|
49 |
+
('?', '?'),
|
50 |
+
('!', '!'),
|
51 |
+
('─‧', '-'),
|
52 |
+
('…', '...'),
|
53 |
+
('《》「」『』〈〉()', "'"),
|
54 |
+
(':︰', ':'),
|
55 |
+
(' ', ' ')
|
56 |
+
]]
|
57 |
+
|
58 |
+
def expand_abbreviations(text):
|
59 |
+
for regex, replacement in _abbreviations:
|
60 |
+
text = re.sub(regex, replacement, text)
|
61 |
+
return text
|
62 |
+
|
63 |
+
def expand_numbers(text):
|
64 |
+
return normalize_numbers(text)
|
65 |
+
|
66 |
+
def lowercase(text):
|
67 |
+
return text.lower()
|
68 |
+
|
69 |
+
def collapse_whitespace(text):
|
70 |
+
return re.sub(_whitespace_re, ' ', text)
|
71 |
+
|
72 |
+
def convert_to_ascii(text):
|
73 |
+
return unidecode(text)
|
74 |
+
|
75 |
+
def english_cleaners(text):
|
76 |
+
'''Pipeline for English text, including abbreviation expansion.'''
|
77 |
+
text = convert_to_ascii(text)
|
78 |
+
#text = lowercase(text)
|
79 |
+
text = expand_numbers(text)
|
80 |
+
text = expand_abbreviations(text)
|
81 |
+
text = collapse_whitespace(text)
|
82 |
+
return text
|
83 |
+
|
84 |
+
def korean_cleaners(text):
|
85 |
+
'''Pipeline for Korean text, including collapses whitespace.'''
|
86 |
+
text = collapse_whitespace(text)
|
87 |
+
text = normalize('NFKD', text)
|
88 |
+
return text
|
89 |
+
|
text/numbers.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" from https://github.com/keithito/tacotron """
|
2 |
+
|
3 |
+
import inflect
|
4 |
+
import re
|
5 |
+
|
6 |
+
|
7 |
+
_inflect = inflect.engine()
|
8 |
+
_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
|
9 |
+
_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
|
10 |
+
_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
|
11 |
+
_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
|
12 |
+
_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
|
13 |
+
_number_re = re.compile(r'[0-9]+')
|
14 |
+
|
15 |
+
|
16 |
+
def _remove_commas(m):
|
17 |
+
return m.group(1).replace(',', '')
|
18 |
+
|
19 |
+
|
20 |
+
def _expand_decimal_point(m):
|
21 |
+
return m.group(1).replace('.', ' point ')
|
22 |
+
|
23 |
+
|
24 |
+
def _expand_dollars(m):
|
25 |
+
match = m.group(1)
|
26 |
+
parts = match.split('.')
|
27 |
+
if len(parts) > 2:
|
28 |
+
return match + ' dollars' # Unexpected format
|
29 |
+
dollars = int(parts[0]) if parts[0] else 0
|
30 |
+
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
|
31 |
+
if dollars and cents:
|
32 |
+
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
33 |
+
cent_unit = 'cent' if cents == 1 else 'cents'
|
34 |
+
return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
|
35 |
+
elif dollars:
|
36 |
+
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
37 |
+
return '%s %s' % (dollars, dollar_unit)
|
38 |
+
elif cents:
|
39 |
+
cent_unit = 'cent' if cents == 1 else 'cents'
|
40 |
+
return '%s %s' % (cents, cent_unit)
|
41 |
+
else:
|
42 |
+
return 'zero dollars'
|
43 |
+
|
44 |
+
|
45 |
+
def _expand_ordinal(m):
|
46 |
+
return _inflect.number_to_words(m.group(0))
|
47 |
+
|
48 |
+
|
49 |
+
def _expand_number(m):
|
50 |
+
num = int(m.group(0))
|
51 |
+
if num > 1000 and num < 3000:
|
52 |
+
if num == 2000:
|
53 |
+
return 'two thousand'
|
54 |
+
elif num > 2000 and num < 2010:
|
55 |
+
return 'two thousand ' + _inflect.number_to_words(num % 100)
|
56 |
+
elif num % 100 == 0:
|
57 |
+
return _inflect.number_to_words(num // 100) + ' hundred'
|
58 |
+
else:
|
59 |
+
return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
|
60 |
+
else:
|
61 |
+
return _inflect.number_to_words(num, andword='')
|
62 |
+
|
63 |
+
|
64 |
+
def normalize_numbers(text):
|
65 |
+
text = re.sub(_comma_number_re, _remove_commas, text)
|
66 |
+
text = re.sub(_pounds_re, r'\1 pounds', text)
|
67 |
+
text = re.sub(_dollars_re, _expand_dollars, text)
|
68 |
+
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
|
69 |
+
text = re.sub(_ordinal_re, _expand_ordinal, text)
|
70 |
+
text = re.sub(_number_re, _expand_number, text)
|
71 |
+
return text
|
text/symbols.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_pad = '_'
|
2 |
+
_punc = ";:,.!?¡¿—-…«»'“”~() "
|
3 |
+
|
4 |
+
_jamo_leads = "".join([chr(_) for _ in range(0x1100, 0x1113)])
|
5 |
+
_jamo_vowels = "".join([chr(_) for _ in range(0x1161, 0x1176)])
|
6 |
+
_jamo_tails = "".join([chr(_) for _ in range(0x11A8, 0x11C3)])
|
7 |
+
_kor_characters = _jamo_leads + _jamo_vowels + _jamo_tails
|
8 |
+
|
9 |
+
_cmu_characters = [
|
10 |
+
'AA', 'AE', 'AH',
|
11 |
+
'AO', 'AW', 'AY',
|
12 |
+
'B', 'CH', 'D', 'DH', 'EH', 'ER', 'EY',
|
13 |
+
'F', 'G', 'HH', 'IH', 'IY',
|
14 |
+
'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OY',
|
15 |
+
'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UW',
|
16 |
+
'V', 'W', 'Y', 'Z', 'ZH'
|
17 |
+
]
|
18 |
+
|
19 |
+
|
20 |
+
lang_to_symbols = {
|
21 |
+
'common': [_pad] + list(_punc),
|
22 |
+
'ko_KR': list(_kor_characters),
|
23 |
+
'en_US': _cmu_characters,
|
24 |
+
}
|
25 |
+
|
26 |
+
def lang_to_dict(lang):
|
27 |
+
symbol_lang = lang_to_symbols['common'] + lang_to_symbols[lang]
|
28 |
+
dict_lang = {s: i for i, s in enumerate(symbol_lang)}
|
29 |
+
return dict_lang
|
30 |
+
|
31 |
+
def lang_to_dict_inverse(lang):
|
32 |
+
symbol_lang = lang_to_symbols['common'] + lang_to_symbols[lang]
|
33 |
+
dict_lang = {i: s for i, s in enumerate(symbol_lang)}
|
34 |
+
return dict_lang
|
35 |
+
|
36 |
+
def symbol_len(lang):
|
37 |
+
symbol_lang = lang_to_symbols['common'] + lang_to_symbols[lang]
|
38 |
+
return len(symbol_lang)
|
transforms.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
|
7 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
8 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
9 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
10 |
+
|
11 |
+
|
12 |
+
def piecewise_rational_quadratic_transform(
|
13 |
+
inputs,
|
14 |
+
unnormalized_widths,
|
15 |
+
unnormalized_heights,
|
16 |
+
unnormalized_derivatives,
|
17 |
+
inverse=False,
|
18 |
+
tails=None,
|
19 |
+
tail_bound=1.,
|
20 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
21 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
22 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE
|
23 |
+
):
|
24 |
+
|
25 |
+
if tails is None:
|
26 |
+
spline_fn = rational_quadratic_spline
|
27 |
+
spline_kwargs = {}
|
28 |
+
else:
|
29 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
30 |
+
spline_kwargs = {
|
31 |
+
'tails': tails,
|
32 |
+
'tail_bound': tail_bound
|
33 |
+
}
|
34 |
+
|
35 |
+
outputs, logabsdet = spline_fn(
|
36 |
+
inputs=inputs,
|
37 |
+
unnormalized_widths=unnormalized_widths,
|
38 |
+
unnormalized_heights=unnormalized_heights,
|
39 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
40 |
+
inverse=inverse,
|
41 |
+
min_bin_width=min_bin_width,
|
42 |
+
min_bin_height=min_bin_height,
|
43 |
+
min_derivative=min_derivative,
|
44 |
+
**spline_kwargs
|
45 |
+
)
|
46 |
+
return outputs, logabsdet
|
47 |
+
|
48 |
+
|
49 |
+
def searchsorted(bin_locations, inputs, eps=1e-6):
|
50 |
+
bin_locations[..., -1] += eps
|
51 |
+
return torch.sum(
|
52 |
+
inputs[..., None] >= bin_locations,
|
53 |
+
dim=-1
|
54 |
+
) - 1
|
55 |
+
|
56 |
+
|
57 |
+
def unconstrained_rational_quadratic_spline(
|
58 |
+
inputs,
|
59 |
+
unnormalized_widths,
|
60 |
+
unnormalized_heights,
|
61 |
+
unnormalized_derivatives,
|
62 |
+
inverse=False,
|
63 |
+
tails='linear',
|
64 |
+
tail_bound=1.,
|
65 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
66 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
67 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE
|
68 |
+
):
|
69 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
70 |
+
outside_interval_mask = ~inside_interval_mask
|
71 |
+
|
72 |
+
outputs = torch.zeros_like(inputs)
|
73 |
+
logabsdet = torch.zeros_like(inputs)
|
74 |
+
|
75 |
+
if tails == 'linear':
|
76 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
77 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
78 |
+
unnormalized_derivatives[..., 0] = constant
|
79 |
+
unnormalized_derivatives[..., -1] = constant
|
80 |
+
|
81 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
82 |
+
logabsdet[outside_interval_mask] = 0
|
83 |
+
else:
|
84 |
+
raise RuntimeError('{} tails are not implemented.'.format(tails))
|
85 |
+
|
86 |
+
outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
|
87 |
+
inputs=inputs[inside_interval_mask],
|
88 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
89 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
90 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
91 |
+
inverse=inverse,
|
92 |
+
left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
|
93 |
+
min_bin_width=min_bin_width,
|
94 |
+
min_bin_height=min_bin_height,
|
95 |
+
min_derivative=min_derivative
|
96 |
+
)
|
97 |
+
|
98 |
+
return outputs, logabsdet
|
99 |
+
|
100 |
+
def rational_quadratic_spline(
|
101 |
+
inputs,
|
102 |
+
unnormalized_widths,
|
103 |
+
unnormalized_heights,
|
104 |
+
unnormalized_derivatives,
|
105 |
+
inverse=False,
|
106 |
+
left=0., right=1., bottom=0., top=1.,
|
107 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
108 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
109 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE
|
110 |
+
):
|
111 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
112 |
+
raise ValueError('Input to a transform is not within its domain')
|
113 |
+
|
114 |
+
num_bins = unnormalized_widths.shape[-1]
|
115 |
+
|
116 |
+
if min_bin_width * num_bins > 1.0:
|
117 |
+
raise ValueError('Minimal bin width too large for the number of bins')
|
118 |
+
if min_bin_height * num_bins > 1.0:
|
119 |
+
raise ValueError('Minimal bin height too large for the number of bins')
|
120 |
+
|
121 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
122 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
123 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
124 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
|
125 |
+
cumwidths = (right - left) * cumwidths + left
|
126 |
+
cumwidths[..., 0] = left
|
127 |
+
cumwidths[..., -1] = right
|
128 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
129 |
+
|
130 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
131 |
+
|
132 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
133 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
134 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
135 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
|
136 |
+
cumheights = (top - bottom) * cumheights + bottom
|
137 |
+
cumheights[..., 0] = bottom
|
138 |
+
cumheights[..., -1] = top
|
139 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
140 |
+
|
141 |
+
if inverse:
|
142 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
143 |
+
else:
|
144 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
145 |
+
|
146 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
147 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
148 |
+
|
149 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
150 |
+
delta = heights / widths
|
151 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
152 |
+
|
153 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
154 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
155 |
+
|
156 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
157 |
+
|
158 |
+
if inverse:
|
159 |
+
a = (((inputs - input_cumheights) * (input_derivatives
|
160 |
+
+ input_derivatives_plus_one
|
161 |
+
- 2 * input_delta)
|
162 |
+
+ input_heights * (input_delta - input_derivatives)))
|
163 |
+
b = (input_heights * input_derivatives
|
164 |
+
- (inputs - input_cumheights) * (input_derivatives
|
165 |
+
+ input_derivatives_plus_one
|
166 |
+
- 2 * input_delta))
|
167 |
+
c = - input_delta * (inputs - input_cumheights)
|
168 |
+
|
169 |
+
discriminant = b.pow(2) - 4 * a * c
|
170 |
+
assert (discriminant >= 0).all()
|
171 |
+
|
172 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
173 |
+
outputs = root * input_bin_widths + input_cumwidths
|
174 |
+
|
175 |
+
theta_one_minus_theta = root * (1 - root)
|
176 |
+
denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
177 |
+
* theta_one_minus_theta)
|
178 |
+
derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
|
179 |
+
+ 2 * input_delta * theta_one_minus_theta
|
180 |
+
+ input_derivatives * (1 - root).pow(2))
|
181 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
182 |
+
|
183 |
+
return outputs, -logabsdet
|
184 |
+
else:
|
185 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
186 |
+
theta_one_minus_theta = theta * (1 - theta)
|
187 |
+
|
188 |
+
numerator = input_heights * (input_delta * theta.pow(2)
|
189 |
+
+ input_derivatives * theta_one_minus_theta)
|
190 |
+
denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
191 |
+
* theta_one_minus_theta)
|
192 |
+
outputs = input_cumheights + numerator / denominator
|
193 |
+
|
194 |
+
derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
|
195 |
+
+ 2 * input_delta * theta_one_minus_theta
|
196 |
+
+ input_derivatives * (1 - theta).pow(2))
|
197 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
198 |
+
|
199 |
+
return outputs, logabsdet
|
utils.py
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from https://github.com/jaywalnut310/vits
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
import logging
|
5 |
+
import subprocess
|
6 |
+
import torch
|
7 |
+
import numpy as np
|
8 |
+
from omegaconf import OmegaConf
|
9 |
+
from scipy.io.wavfile import read
|
10 |
+
|
11 |
+
MATPLOTLIB_FLAG = False
|
12 |
+
|
13 |
+
logging.basicConfig(
|
14 |
+
stream=sys.stdout,
|
15 |
+
level=logging.INFO,
|
16 |
+
format='[%(levelname)s|%(filename)s:%(lineno)s][%(asctime)s] >>> %(message)s'
|
17 |
+
)
|
18 |
+
logger = logging
|
19 |
+
|
20 |
+
|
21 |
+
def load_checkpoint(checkpoint_path, rank=0, model_g=None, model_d=None, optim_g=None, optim_d=None):
|
22 |
+
assert os.path.isfile(checkpoint_path)
|
23 |
+
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
|
24 |
+
iteration = checkpoint_dict['iteration']
|
25 |
+
learning_rate = checkpoint_dict['learning_rate']
|
26 |
+
config = checkpoint_dict['config']
|
27 |
+
|
28 |
+
if model_g is not None:
|
29 |
+
model_g, optim_g = load_model(
|
30 |
+
model_g,
|
31 |
+
checkpoint_dict['model_g'],
|
32 |
+
optim_g,
|
33 |
+
checkpoint_dict['optimizer_g'])
|
34 |
+
|
35 |
+
if model_d is not None:
|
36 |
+
model_d, optim_d = load_model(
|
37 |
+
model_d,
|
38 |
+
checkpoint_dict['model_d'],
|
39 |
+
optim_d,
|
40 |
+
checkpoint_dict['optimizer_d'])
|
41 |
+
if rank == 0:
|
42 |
+
logger.info(
|
43 |
+
"Loaded checkpoint '{}' (iteration {})".format(
|
44 |
+
checkpoint_path,
|
45 |
+
iteration
|
46 |
+
)
|
47 |
+
)
|
48 |
+
return model_g, model_d, optim_g, optim_d, learning_rate, iteration, config
|
49 |
+
|
50 |
+
def load_checkpoint_diffsize(checkpoint_path, rank=0, model_g=None, model_d=None):
|
51 |
+
assert os.path.isfile(checkpoint_path)
|
52 |
+
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
|
53 |
+
iteration = checkpoint_dict['iteration']
|
54 |
+
learning_rate = checkpoint_dict['learning_rate']
|
55 |
+
config = checkpoint_dict['config']
|
56 |
+
|
57 |
+
if model_g is not None:
|
58 |
+
model_g = load_model_diffsize(
|
59 |
+
model_g,
|
60 |
+
checkpoint_dict['model_g'])
|
61 |
+
if model_d is not None:
|
62 |
+
model_d = load_model_diffsize(
|
63 |
+
model_d,
|
64 |
+
checkpoint_dict['model_d'])
|
65 |
+
if rank == 0:
|
66 |
+
logger.info(
|
67 |
+
"Loaded checkpoint '{}' (iteration {})".format(
|
68 |
+
checkpoint_path,
|
69 |
+
iteration
|
70 |
+
)
|
71 |
+
)
|
72 |
+
del checkpoint_dict
|
73 |
+
return model_g, model_d, learning_rate, iteration, config
|
74 |
+
|
75 |
+
def load_model_diffsize(model, model_state_dict):
|
76 |
+
if hasattr(model, 'module'):
|
77 |
+
state_dict = model.module.state_dict()
|
78 |
+
else:
|
79 |
+
state_dict = model.state_dict()
|
80 |
+
|
81 |
+
for k, v in model_state_dict.items():
|
82 |
+
if k in state_dict and state_dict[k].size() == v.size():
|
83 |
+
state_dict[k] = v
|
84 |
+
|
85 |
+
if hasattr(model, 'module'):
|
86 |
+
model.module.load_state_dict(state_dict, strict=False)
|
87 |
+
else:
|
88 |
+
model.load_state_dict(state_dict, strict=False)
|
89 |
+
|
90 |
+
return model
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
def load_model(model, model_state_dict, optim, optim_state_dict):
|
95 |
+
if optim is not None:
|
96 |
+
optim.load_state_dict(optim_state_dict)
|
97 |
+
|
98 |
+
if hasattr(model, 'module'):
|
99 |
+
state_dict = model.module.state_dict()
|
100 |
+
else:
|
101 |
+
state_dict = model.state_dict()
|
102 |
+
|
103 |
+
for k, v in model_state_dict.items():
|
104 |
+
if k in state_dict and state_dict[k].size() == v.size():
|
105 |
+
state_dict[k] = v
|
106 |
+
|
107 |
+
if hasattr(model, 'module'):
|
108 |
+
model.module.load_state_dict(state_dict)
|
109 |
+
else:
|
110 |
+
model.load_state_dict(state_dict)
|
111 |
+
|
112 |
+
return model, optim
|
113 |
+
|
114 |
+
|
115 |
+
def save_checkpoint(net_g, optim_g, net_d, optim_d, hps, epoch, learning_rate, save_path):
|
116 |
+
|
117 |
+
def get_state_dict(model):
|
118 |
+
if hasattr(model, 'module'):
|
119 |
+
state_dict = model.module.state_dict()
|
120 |
+
else:
|
121 |
+
state_dict = model.state_dict()
|
122 |
+
return state_dict
|
123 |
+
|
124 |
+
torch.save({'model_g': get_state_dict(net_g),
|
125 |
+
'model_d': get_state_dict(net_d),
|
126 |
+
'optimizer_g': optim_g.state_dict(),
|
127 |
+
'optimizer_d': optim_d.state_dict(),
|
128 |
+
'config': str(hps),
|
129 |
+
'iteration': epoch,
|
130 |
+
'learning_rate': learning_rate}, save_path)
|
131 |
+
|
132 |
+
|
133 |
+
def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
|
134 |
+
for k, v in scalars.items():
|
135 |
+
writer.add_scalar(k, v, global_step)
|
136 |
+
for k, v in histograms.items():
|
137 |
+
writer.add_histogram(k, v, global_step)
|
138 |
+
for k, v in images.items():
|
139 |
+
writer.add_image(k, v, global_step, dataformats='HWC')
|
140 |
+
for k, v in audios.items():
|
141 |
+
writer.add_audio(k, v, global_step, audio_sampling_rate)
|
142 |
+
|
143 |
+
|
144 |
+
def plot_spectrogram_to_numpy(spectrogram):
|
145 |
+
global MATPLOTLIB_FLAG
|
146 |
+
if not MATPLOTLIB_FLAG:
|
147 |
+
import matplotlib
|
148 |
+
matplotlib.use("Agg")
|
149 |
+
MATPLOTLIB_FLAG = True
|
150 |
+
mpl_logger = logging.getLogger('matplotlib')
|
151 |
+
mpl_logger.setLevel(logging.WARNING)
|
152 |
+
import matplotlib.pylab as plt
|
153 |
+
import numpy as np
|
154 |
+
|
155 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
156 |
+
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
|
157 |
+
interpolation='none')
|
158 |
+
plt.colorbar(im, ax=ax)
|
159 |
+
plt.xlabel("Frames")
|
160 |
+
plt.ylabel("Channels")
|
161 |
+
plt.tight_layout()
|
162 |
+
|
163 |
+
fig.canvas.draw()
|
164 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
|
165 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
166 |
+
plt.close()
|
167 |
+
return data
|
168 |
+
|
169 |
+
|
170 |
+
def plot_alignment_to_numpy(alignment, info=None):
|
171 |
+
global MATPLOTLIB_FLAG
|
172 |
+
if not MATPLOTLIB_FLAG:
|
173 |
+
import matplotlib
|
174 |
+
matplotlib.use("Agg")
|
175 |
+
MATPLOTLIB_FLAG = True
|
176 |
+
mpl_logger = logging.getLogger('matplotlib')
|
177 |
+
mpl_logger.setLevel(logging.WARNING)
|
178 |
+
import matplotlib.pylab as plt
|
179 |
+
import numpy as np
|
180 |
+
|
181 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
182 |
+
im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
|
183 |
+
interpolation='none')
|
184 |
+
fig.colorbar(im, ax=ax)
|
185 |
+
xlabel = 'Decoder timestep'
|
186 |
+
if info is not None:
|
187 |
+
xlabel += '\n\n' + info
|
188 |
+
plt.xlabel(xlabel)
|
189 |
+
plt.ylabel('Encoder timestep')
|
190 |
+
plt.tight_layout()
|
191 |
+
|
192 |
+
fig.canvas.draw()
|
193 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
|
194 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
195 |
+
plt.close()
|
196 |
+
return data
|
197 |
+
|
198 |
+
|
199 |
+
def load_wav_to_torch(full_path):
|
200 |
+
sampling_rate, wav = read(full_path)
|
201 |
+
|
202 |
+
if len(wav.shape) == 2:
|
203 |
+
wav = wav[:, 0]
|
204 |
+
|
205 |
+
if wav.dtype == np.int16:
|
206 |
+
wav = wav / 32768.0
|
207 |
+
elif wav.dtype == np.int32:
|
208 |
+
wav = wav / 2147483648.0
|
209 |
+
elif wav.dtype == np.uint8:
|
210 |
+
wav = (wav - 128) / 128.0
|
211 |
+
wav = wav.astype(np.float32)
|
212 |
+
return torch.FloatTensor(wav), sampling_rate
|
213 |
+
|
214 |
+
|
215 |
+
def load_filepaths_and_text(filename, split="|"):
|
216 |
+
with open(filename, encoding='utf-8') as f:
|
217 |
+
filepaths_and_text = [line.strip().split(split) for line in f]
|
218 |
+
return filepaths_and_text
|
219 |
+
|
220 |
+
|
221 |
+
def get_hparams(args, init=True):
|
222 |
+
config = OmegaConf.load(args.config)
|
223 |
+
hparams = HParams(**config)
|
224 |
+
model_dir = os.path.join(hparams.train.log_path, args.model)
|
225 |
+
|
226 |
+
if not os.path.exists(model_dir):
|
227 |
+
os.makedirs(model_dir)
|
228 |
+
hparams.model_name = args.model
|
229 |
+
hparams.model_dir = model_dir
|
230 |
+
config_save_path = os.path.join(model_dir, "config.yaml")
|
231 |
+
|
232 |
+
if init:
|
233 |
+
OmegaConf.save(config, config_save_path)
|
234 |
+
|
235 |
+
return hparams
|
236 |
+
|
237 |
+
|
238 |
+
def get_hparams_from_file(config_path):
|
239 |
+
config = OmegaConf.load(config_path)
|
240 |
+
hparams = HParams(**config)
|
241 |
+
return hparams
|
242 |
+
|
243 |
+
|
244 |
+
def check_git_hash(model_dir):
|
245 |
+
source_dir = os.path.dirname(os.path.realpath(__file__))
|
246 |
+
if not os.path.exists(os.path.join(source_dir, ".git")):
|
247 |
+
logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
|
248 |
+
source_dir
|
249 |
+
))
|
250 |
+
return
|
251 |
+
|
252 |
+
cur_hash = subprocess.getoutput("git rev-parse HEAD")
|
253 |
+
|
254 |
+
path = os.path.join(model_dir, "githash")
|
255 |
+
if os.path.exists(path):
|
256 |
+
saved_hash = open(path).read()
|
257 |
+
if saved_hash != cur_hash:
|
258 |
+
logger.warn("git hash values are different. {}(saved) != {}(current)".format(
|
259 |
+
saved_hash[:8], cur_hash[:8]))
|
260 |
+
else:
|
261 |
+
open(path, "w").write(cur_hash)
|
262 |
+
|
263 |
+
|
264 |
+
def get_logger(model_dir, filename="train.log"):
|
265 |
+
global logger
|
266 |
+
logger = logging.getLogger(os.path.basename(model_dir))
|
267 |
+
logger.setLevel(logging.DEBUG)
|
268 |
+
|
269 |
+
formatter = logging.Formatter(
|
270 |
+
"%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
|
271 |
+
if not os.path.exists(model_dir):
|
272 |
+
os.makedirs(model_dir)
|
273 |
+
h = logging.FileHandler(os.path.join(model_dir, filename))
|
274 |
+
h.setLevel(logging.DEBUG)
|
275 |
+
h.setFormatter(formatter)
|
276 |
+
logger.addHandler(h)
|
277 |
+
return logger
|
278 |
+
|
279 |
+
|
280 |
+
class HParams():
|
281 |
+
def __init__(self, **kwargs):
|
282 |
+
for k, v in kwargs.items():
|
283 |
+
if type(v) == dict:
|
284 |
+
v = HParams(**v)
|
285 |
+
self[k] = v
|
286 |
+
|
287 |
+
def keys(self):
|
288 |
+
return self.__dict__.keys()
|
289 |
+
|
290 |
+
def items(self):
|
291 |
+
return self.__dict__.items()
|
292 |
+
|
293 |
+
def values(self):
|
294 |
+
return self.__dict__.values()
|
295 |
+
|
296 |
+
def __len__(self):
|
297 |
+
return len(self.__dict__)
|
298 |
+
|
299 |
+
def __getitem__(self, key):
|
300 |
+
return getattr(self, key)
|
301 |
+
|
302 |
+
def __setitem__(self, key, value):
|
303 |
+
return setattr(self, key, value)
|
304 |
+
|
305 |
+
def __contains__(self, key):
|
306 |
+
return key in self.__dict__
|
307 |
+
|
308 |
+
def __repr__(self):
|
309 |
+
return self.__dict__.__repr__()
|
yin.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# remove np from https://github.com/dhchoi99/NANSY/blob/master/models/yin.py
|
2 |
+
# adapted from https://github.com/patriceguyot/Yin
|
3 |
+
# https://github.com/NVIDIA/mellotron/blob/master/yin.py
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from math import log2, ceil
|
8 |
+
|
9 |
+
|
10 |
+
def differenceFunction(x, N, tau_max):
|
11 |
+
"""
|
12 |
+
Compute difference function of data x. This corresponds to equation (6) in [1]
|
13 |
+
This solution is implemented directly with torch rfft.
|
14 |
+
|
15 |
+
|
16 |
+
:param x: audio data (Tensor)
|
17 |
+
:param N: length of data
|
18 |
+
:param tau_max: integration window size
|
19 |
+
:return: difference function
|
20 |
+
:rtype: list
|
21 |
+
"""
|
22 |
+
|
23 |
+
#x = np.array(x, np.float64) #[B,T]
|
24 |
+
assert x.dim() == 2
|
25 |
+
b, w = x.shape
|
26 |
+
if w < tau_max:
|
27 |
+
x = F.pad(x, (tau_max - w - (tau_max - w) // 2, (tau_max - w) // 2),
|
28 |
+
'constant',
|
29 |
+
mode='reflect')
|
30 |
+
w = tau_max
|
31 |
+
#x_cumsum = np.concatenate((np.array([0.]), (x * x).cumsum()))
|
32 |
+
x_cumsum = torch.cat(
|
33 |
+
[torch.zeros([b, 1], device=x.device), (x * x).cumsum(dim=1)], dim=1)
|
34 |
+
size = w + tau_max
|
35 |
+
p2 = (size // 32).bit_length()
|
36 |
+
#p2 = ceil(log2(size+1 // 32))
|
37 |
+
nice_numbers = (16, 18, 20, 24, 25, 27, 30, 32)
|
38 |
+
size_pad = min(n * 2**p2 for n in nice_numbers if n * 2**p2 >= size)
|
39 |
+
fc = torch.fft.rfft(x, size_pad) #[B,F]
|
40 |
+
conv = torch.fft.irfft(fc * fc.conj())[:, :tau_max]
|
41 |
+
return x_cumsum[:, w:w - tau_max:
|
42 |
+
-1] + x_cumsum[:, w] - x_cumsum[:, :tau_max] - 2 * conv
|
43 |
+
|
44 |
+
|
45 |
+
def differenceFunction_np(x, N, tau_max):
|
46 |
+
"""
|
47 |
+
Compute difference function of data x. This corresponds to equation (6) in [1]
|
48 |
+
This solution is implemented directly with Numpy fft.
|
49 |
+
|
50 |
+
|
51 |
+
:param x: audio data
|
52 |
+
:param N: length of data
|
53 |
+
:param tau_max: integration window size
|
54 |
+
:return: difference function
|
55 |
+
:rtype: list
|
56 |
+
"""
|
57 |
+
|
58 |
+
x = np.array(x, np.float64)
|
59 |
+
w = x.size
|
60 |
+
tau_max = min(tau_max, w)
|
61 |
+
x_cumsum = np.concatenate((np.array([0.]), (x * x).cumsum()))
|
62 |
+
size = w + tau_max
|
63 |
+
p2 = (size // 32).bit_length()
|
64 |
+
nice_numbers = (16, 18, 20, 24, 25, 27, 30, 32)
|
65 |
+
size_pad = min(x * 2**p2 for x in nice_numbers if x * 2**p2 >= size)
|
66 |
+
fc = np.fft.rfft(x, size_pad)
|
67 |
+
conv = np.fft.irfft(fc * fc.conjugate())[:tau_max]
|
68 |
+
return x_cumsum[w:w -
|
69 |
+
tau_max:-1] + x_cumsum[w] - x_cumsum[:tau_max] - 2 * conv
|
70 |
+
|
71 |
+
|
72 |
+
def cumulativeMeanNormalizedDifferenceFunction(df, N, eps=1e-8):
|
73 |
+
"""
|
74 |
+
Compute cumulative mean normalized difference function (CMND).
|
75 |
+
|
76 |
+
This corresponds to equation (8) in [1]
|
77 |
+
|
78 |
+
:param df: Difference function
|
79 |
+
:param N: length of data
|
80 |
+
:return: cumulative mean normalized difference function
|
81 |
+
:rtype: list
|
82 |
+
"""
|
83 |
+
#np.seterr(divide='ignore', invalid='ignore')
|
84 |
+
# scipy method, assert df>0 for all element
|
85 |
+
# cmndf = df[1:] * np.asarray(list(range(1, N))) / (np.cumsum(df[1:]).astype(float) + eps)
|
86 |
+
B, _ = df.shape
|
87 |
+
cmndf = df[:,
|
88 |
+
1:] * torch.arange(1, N, device=df.device, dtype=df.dtype).view(
|
89 |
+
1, -1) / (df[:, 1:].cumsum(dim=-1) + eps)
|
90 |
+
return torch.cat(
|
91 |
+
[torch.ones([B, 1], device=df.device, dtype=df.dtype), cmndf], dim=-1)
|
92 |
+
|
93 |
+
|
94 |
+
def differenceFunctionTorch(xs: torch.Tensor, N, tau_max) -> torch.Tensor:
|
95 |
+
"""pytorch backend batch-wise differenceFunction
|
96 |
+
has 1e-4 level error with input shape of (32, 22050*1.5)
|
97 |
+
Args:
|
98 |
+
xs:
|
99 |
+
N:
|
100 |
+
tau_max:
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
|
104 |
+
"""
|
105 |
+
xs = xs.double()
|
106 |
+
w = xs.shape[-1]
|
107 |
+
tau_max = min(tau_max, w)
|
108 |
+
zeros = torch.zeros((xs.shape[0], 1))
|
109 |
+
x_cumsum = torch.cat((torch.zeros((xs.shape[0], 1), device=xs.device),
|
110 |
+
(xs * xs).cumsum(dim=-1, dtype=torch.double)),
|
111 |
+
dim=-1) # B x w
|
112 |
+
size = w + tau_max
|
113 |
+
p2 = (size // 32).bit_length()
|
114 |
+
nice_numbers = (16, 18, 20, 24, 25, 27, 30, 32)
|
115 |
+
size_pad = min(x * 2**p2 for x in nice_numbers if x * 2**p2 >= size)
|
116 |
+
|
117 |
+
fcs = torch.fft.rfft(xs, n=size_pad, dim=-1)
|
118 |
+
convs = torch.fft.irfft(fcs * fcs.conj())[:, :tau_max]
|
119 |
+
y1 = torch.flip(x_cumsum[:, w - tau_max + 1:w + 1], dims=[-1])
|
120 |
+
y = y1 + x_cumsum[:, w].unsqueeze(-1) - x_cumsum[:, :tau_max] - 2 * convs
|
121 |
+
return y
|
122 |
+
|
123 |
+
|
124 |
+
def cumulativeMeanNormalizedDifferenceFunctionTorch(dfs: torch.Tensor,
|
125 |
+
N,
|
126 |
+
eps=1e-8) -> torch.Tensor:
|
127 |
+
arange = torch.arange(1, N, device=dfs.device, dtype=torch.float64)
|
128 |
+
cumsum = torch.cumsum(dfs[:, 1:], dim=-1,
|
129 |
+
dtype=torch.float64).to(dfs.device)
|
130 |
+
|
131 |
+
cmndfs = dfs[:, 1:] * arange / (cumsum + eps)
|
132 |
+
cmndfs = torch.cat(
|
133 |
+
(torch.ones(cmndfs.shape[0], 1, device=dfs.device), cmndfs), dim=-1)
|
134 |
+
return cmndfs
|
135 |
+
|
136 |
+
|
137 |
+
if __name__ == '__main__':
|
138 |
+
wav = torch.randn(32, int(22050 * 1.5)).cuda()
|
139 |
+
wav_numpy = wav.detach().cpu().numpy()
|
140 |
+
x = wav_numpy[0]
|
141 |
+
|
142 |
+
w_len = 2048
|
143 |
+
w_step = 256
|
144 |
+
tau_max = 2048
|
145 |
+
W = 2048
|
146 |
+
|
147 |
+
startFrames = list(range(0, x.shape[-1] - w_len, w_step))
|
148 |
+
startFrames = np.asarray(startFrames)
|
149 |
+
# times = startFrames / sr
|
150 |
+
frames = [x[..., t:t + W] for t in startFrames]
|
151 |
+
frames = np.asarray(frames)
|
152 |
+
frames_torch = torch.from_numpy(frames).cuda()
|
153 |
+
|
154 |
+
cmndfs0 = []
|
155 |
+
for idx, frame in enumerate(frames):
|
156 |
+
df = differenceFunction(frame, frame.shape[-1], tau_max)
|
157 |
+
cmndf = cumulativeMeanNormalizedDifferenceFunction(df, tau_max)
|
158 |
+
cmndfs0.append(cmndf)
|
159 |
+
cmndfs0 = np.asarray(cmndfs0)
|
160 |
+
|
161 |
+
dfs = differenceFunctionTorch(frames_torch, frames_torch.shape[-1],
|
162 |
+
tau_max)
|
163 |
+
cmndfs1 = cumulativeMeanNormalizedDifferenceFunctionTorch(
|
164 |
+
dfs, tau_max).detach().cpu().numpy()
|
165 |
+
print(cmndfs0.shape, cmndfs1.shape)
|
166 |
+
print(np.sum(np.abs(cmndfs0 - cmndfs1)))
|