File size: 8,547 Bytes
11b4f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import torch
import torch.nn as nn
import torch.optim as optim
import pytorch_lightning.core.module as pl
import matplotlib.pyplot as plt
from module import commons

from transformer.embedding import SinePositionalEmbedding
from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
plt.switch_backend('agg')
from module.models import SynthesizerTrn
from module.modules import MelStyleEncoder

def init_vits_s2(config_path, cpt_path):
    import utils
    hps = utils.get_hparams_from_file(config_path)

    vits_s2 = SynthesizerTrn(
        hps.data.filter_length // 2 + 1,
        hps.train.segment_size // hps.data.hop_length,
        n_speakers=hps.data.n_speakers,
        **hps.model)
    ckpt = torch.load(cpt_path, map_location='cpu')['model']
    vits_s2.load_state_dict(ckpt)
    vits_s2.eval()
    return vits_s2

import math
import torch.nn.functional as F
from tqdm import tqdm

class SinusoidalPosEmb(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim

    def forward(self, x):
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
        emb = x[:, None] * emb[None, :]
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb

class DiT(nn.Module):
    def __init__(self, io_channels, cond_channels):
        super().__init__()
        self.in_proj = nn.Linear(io_channels+cond_channels, 512)
        norm_first = False
        self.position = SinePositionalEmbedding(
            512, dropout=0.1, scale=False, alpha=True)
        self.encoder = TransformerEncoder(
            TransformerEncoderLayer(
                d_model=512,
                nhead=16,
                dim_feedforward=2048,
                dropout=0.1,
                batch_first=True,
                norm_first=False, ),
            num_layers=12,
            norm=LayerNorm(512) if norm_first else None, )
        self.proj = nn.Linear(512, io_channels)
        self.diffusion_embedding = SinusoidalPosEmb(512)


    def forward(self, x, t, cond, mask=None):
        if mask is None:
            mask = torch.ones(x.shape[0], x.shape[-1], device=x.device).long()
        mask_bool = ~mask.bool()
        diffusion_step = self.diffusion_embedding(t).unsqueeze(1)
        x = torch.cat([x, cond], dim=1).transpose(1, 2)
        x = self.in_proj(x)
        x = torch.cat([diffusion_step, x], dim=1)
        mask_bool = torch.cat([torch.zeros([mask_bool.shape[0], 1], device=mask_bool.device).bool(), mask_bool], dim=1)
        x = self.position(x)
        x, _ = self.encoder(
            (x, None), src_key_padding_mask=mask_bool)
        x = x[:, 1:, :]
        x = self.proj(x).transpose(1, 2)
        return x

class ReFlow(nn.Module):
    def __init__(self,
                 io_channels,
                 cond_channels,
                 ):
        super().__init__()
        self.model = DiT(io_channels, cond_channels)
        self.io_channels = io_channels
        self.rng = torch.quasirandom.SobolEngine(1, scramble=True)

    def forward(self, reals, cond, mask):
        # reals : [B, 128, T]
        # cond : [B, 192, T]
        # mask : [B, 1, T]
        t = self.rng.draw(reals.shape[0])[:, 0].to(reals.device)

        alphas, sigmas = 1 - t, t
        alphas = alphas[:, None, None]
        sigmas = sigmas[:, None, None]

        noise = torch.randn_like(reals)
        noised_inputs = reals * alphas + noise * sigmas

        targets = noise - reals

        output = self.model(noised_inputs, t, cond, mask)
        # mse loss with mask
        loss = F.mse_loss(output, targets, reduction='none')
        loss = loss * mask.unsqueeze(1)

        return loss.mean()

    def sample(self, cond, uncond, steps, guidance, sigma_max=1):
        x = torch.randn(cond.shape[0], self.io_channels, cond.shape[2]).to(cond.device)
        t = torch.linspace(sigma_max, 0, steps + 1)

        for t_curr, t_prev in tqdm(zip(t[:-1], t[1:])):
            t_curr_tensor = t_curr * torch.ones(
                (x.shape[0],), dtype=x.dtype, device=x.device
            )
            dt = t_prev - t_curr
            v_cond = self.model(x, t_curr_tensor, cond)
            v_uncond = self.model(x, t_curr_tensor, uncond)
            v = guidance * v_cond + (1 - guidance) * v_uncond
            x = x + dt *  v
        return x

class NARPredictor(nn.Module):
    def __init__(self, latent_dim=16):
        super().__init__()

        self.latent_dim = latent_dim
        self.bert_proj = nn.Linear(1024, 192)
        self.x_emb = nn.Linear(192, 192)
        self.ref_enc = MelStyleEncoder(latent_dim, style_vector_dim=192)
        self.null_emb = nn.Parameter(torch.randn(192))


        
        self.reflow = ReFlow(latent_dim, 192)


    def forward(self, x, bert, spk_emb, diffusion_input, mask):
        g = self.ref_enc(diffusion_input, mask.float().unsqueeze(1)).transpose(1, 2)
        bert = self.bert_proj(bert.transpose(1, 2))
        x = self.x_emb(x.transpose(1,2))

        cond = (x + bert + g).transpose(1, 2) # [B, 192, T]
        # dropout prob 0.1
        for b in range(cond.shape[0]):
            if torch.rand(1) < 0.1:
                cond[b, :, :] = self.null_emb.unsqueeze(1).expand(-1, cond.shape[2])

        loss = self.reflow(diffusion_input, cond, mask)

        return loss

    @torch.inference_mode()
    @torch.no_grad()
    def infer(self, x, bert, prompt, step, guidance):

        g = self.ref_enc(prompt).transpose(1, 2)
        bert = self.bert_proj(bert.transpose(1, 2))
        x = self.x_emb(x.transpose(1,2))
        cond = (x + bert + g).transpose(1, 2)
        uncond = self.null_emb.unsqueeze(1).expand(-1, cond.shape[2]).unsqueeze(0)

        fakes = self.reflow.sample(cond,uncond, step, guidance)


        return fakes


class Wav2TTS(pl.LightningModule):
    def __init__(self, hp, vits_s2=None):
        super().__init__()
        self.model = NARPredictor(latent_dim=4)
        self.lr = hp.lr
        if vits_s2 is None:
            vits_s2 = init_vits_s2('configs/vits.json', 'logs/vits/G_38100.pth')
        self.s2 = [vits_s2]
        self.inited = False


    def configure_optimizers(self):
        print('train with lr ', self.lr)
        optimizer = optim.AdamW([*self.parameters()], lr=self.lr, betas=(0.9, 0.95), weight_decay=0.1)
        return optimizer

    def training_step(self, batch, batch_idx):
        loss = self.step(batch)
        self.log("train/loss", loss, on_step=True, prog_bar=True)
        # self.log("train/quantize_loss", quantize_loss, on_step=True, prog_bar=True)
        return loss

    def validation_step(self, batch, batch_idx):
        loss = self.step(batch)
        self.log("val/loss", loss, on_step=True, prog_bar=True)

    def step(self, batch):
        # speaker_embedding = self.spk_proj(batch['spk_emb'])
        # speaker_embedding, commitment_loss, codebook_loss, indices, z_e = self.spk_vq(speaker_embedding.unsqueeze(-1))
        # quantize_loss = codebook_loss + 0.25*commitment_loss
        # speaker_embedding = speaker_embedding.squeeze(-1)
        # speaker_embedding = self.spk_emb(batch['spk_emb'])
        # Deal with phone segments
        phone = batch['phone']
        lengths = batch['length']
        bert_feature = batch['bert_feature']
        speaker_embedding = batch['spk_emb']
        latent = batch['latent']
        mask = commons.sequence_mask(lengths, latent.size(-1)).long() # [1,1,1,1,0...]

        if not self.inited:
            self.s2 = [self.s2[0].to(phone.device)]
            self.inited = True
        
        s2 = self.s2[0]
        phone_features, _ = s2.enc_p(phone, mask.unsqueeze(1))


        loss = self.model(phone_features, bert_feature, speaker_embedding,  latent, mask)
        return loss

    @torch.inference_mode()
    @torch.no_grad()
    def inference(self, phonemes,  bert_feature, prompt, n_steps=32, guidance=4):
        # speaker_embedding = self.spk_proj(spk_emb)
        # speaker_embedding, commitment_loss, codebook_loss, indices, z_e = self.spk_vq(speaker_embedding.unsqueeze(-1))
        # speaker_embedding = speaker_embedding.squeeze(-1)
        # print('quantized spk code:', indices)
        mask = torch.ones(phonemes.shape[0],1,  phonemes.shape[1]).to(phonemes.device).float()
        s2 = self.s2[0]
        phone_features, _ = s2.enc_p(phonemes, mask)
        output = self.model.infer(phone_features, bert_feature, prompt, n_steps, guidance)
        return output