File size: 10,927 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from omegaconf import OmegaConf
from module.aligner import AlignmentEncoder
from module.maskgit import ImageBert, MLMLoss
from module.wavenet import SinusoidalPosEmb, WaveNet
from text import symbols
from transformer.embedding import SinePositionalEmbedding
from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from module.models import TextEncoder, PosteriorEncoder, FramePriorNet, Generator, ProsodyEncoder, ResidualCouplingBlock, mono_align_and_get_loss
from module import commons
from module import modules
import math


import random
from tqdm import tqdm


class NARPredictor(nn.Module):
    def __init__(self, codebook_size=128, gin_channels=0):
        super().__init__()
        conf = {
            "model": {
                "vq_model": {
                    "codebook_size": codebook_size,
                    "token_size": 12,
                    "use_l2_norm": True,
                    "commitment_cost": 0.25,
                    "vit_enc_model_size": "base",
                    "vit_dec_model_size": "base",
                    "vit_enc_patch_size": 16,
                    "vit_dec_patch_size": 16,
                    "num_latent_tokens": 64,
                    "finetune_decoder": True
                },
                "generator": {
                    "model_type": "ViT",
                    "hidden_size": 512,
                    "num_hidden_layers": 12,
                    "num_attention_heads": 16,
                    "intermediate_size": 2048,
                    "dropout": 0.1,
                    "attn_drop": 0.1,
                    "num_steps": 8,
                    "class_label_dropout": 0.1,
                    "image_seq_len": 2048,
                    "condition_dim": 192,
                    "randomize_temperature": 1.0,
                    "guidance_scale": 4.5,
                    "guidance_decay": "constant"
                }

            },
            "losses": {
                "label_smoothing": 0.1,
                "loss_weight_unmasked_token": 0.1
            }

        }
        config = OmegaConf.create(conf)

        self.bert_proj = nn.Linear(1024, 192)
        self.ph_emb = nn.Embedding(1024, 192)
        self.g_emb = nn.Linear(256, 192)
        self.loss_module = MLMLoss(config)
        self.model = ImageBert(config)


    def forward(self, x, x_mask, bert, spk_emb, tgt_code):
        g = self.g_emb(spk_emb).unsqueeze(1)
        bert = self.bert_proj(bert.transpose(1, 2))
        ph = self.ph_emb(x)

        conditions = ph + bert + g
        input_tokens = tgt_code

        masked_tokens, masks = self.model.masking_input_tokens(
            input_tokens)
        logits = self.model(masked_tokens, conditions,
                    cond_drop_prob=0.1)

        masks = masks & (x_mask.squeeze(1).bool())
        loss, loss_dict = self.loss_module(logits, input_tokens, weights=masks)
        print('acc:', loss_dict['correct_tokens'])
        return loss

    @torch.inference_mode()
    @torch.no_grad()
    def infer(self, x, x_mask, bert, spk_emb, step=5, sched_mode="square", temp=30, randomize="None", r_temp=30, cfg_scale=1.5):

        g = self.g_emb(spk_emb).unsqueeze(1)
        bert = self.bert_proj(bert.transpose(1, 2))
        ph = self.ph_emb(x)

        conditions = ph + bert + g
        code = self.model.generate(
            conditions,
            guidance_scale=0.5,
        )
        return code

    def adap_sche(self, step, mode="arccos", leave=False, tgt_length=None):
        """ Create a sampling scheduler
           :param
            step  -> int:  number of prediction during inference
            mode  -> str:  the rate of value to unmask
            leave -> bool: tqdm arg on either to keep the bar or not
           :return
            scheduler -> torch.LongTensor(): the list of token to predict at each step
        """
        r = torch.linspace(1, 0, step)
        if mode == "root":  # root scheduler
            val_to_mask = 1 - (r ** .5)
        elif mode == "linear":  # linear scheduler
            val_to_mask = 1 - r
        elif mode == "square":  # square scheduler
            val_to_mask = 1 - (r ** 2)
        elif mode == "cosine":  # cosine scheduler
            val_to_mask = torch.cos(r * math.pi * 0.5)
        elif mode == "arccos":  # arc cosine scheduler
            val_to_mask = torch.arccos(r) / (math.pi * 0.5)
        else:
            return

        # fill the scheduler by the ratio of tokens to predict at each step
        sche = (val_to_mask / val_to_mask.sum()) * tgt_length
        sche = sche.round()
        sche[sche == 0] = 1  # add 1 to predict a least 1 token / step
        sche[-1] += tgt_length - sche.sum()  # need to sum up nb of code
        return tqdm(sche.int(), leave=leave)


class SynthesizerTrn(nn.Module):
    """
      Synthesizer for Training
    """

    def __init__(self,
                 spec_channels,
                 segment_size,
                 inter_channels,
                 hidden_channels,
                 filter_channels,
                 n_heads,
                 n_layers,
                 kernel_size,
                 p_dropout,
                 resblock,
                 resblock_kernel_sizes,
                 resblock_dilation_sizes,
                 upsample_rates,
                 upsample_initial_channel,
                 upsample_kernel_sizes,
                 n_speakers=0,
                 gin_channels=0,
                 use_sdp=True,
                 freeze_quantizer=False,
                 **kwargs):
        super().__init__()
        self.spec_channels = spec_channels
        self.inter_channels = inter_channels
        self.hidden_channels = hidden_channels
        self.filter_channels = filter_channels
        self.n_heads = n_heads
        self.n_layers = n_layers
        self.kernel_size = kernel_size
        self.p_dropout = p_dropout
        self.resblock = resblock
        self.resblock_kernel_sizes = resblock_kernel_sizes
        self.resblock_dilation_sizes = resblock_dilation_sizes
        self.upsample_rates = upsample_rates
        self.upsample_initial_channel = upsample_initial_channel
        self.upsample_kernel_sizes = upsample_kernel_sizes
        self.segment_size = segment_size
        self.n_speakers = n_speakers

        gin_channels = hidden_channels
        self.gin_channels = gin_channels

        self.use_sdp = use_sdp

        self.enc_p = TextEncoder(inter_channels,
                                 hidden_channels,
                                 filter_channels,
                                 n_heads,
                                 n_layers,
                                 kernel_size,
                                 p_dropout)
        print('n_param of enc_p', sum(p.numel() for p in self.enc_p.parameters() if p.requires_grad) / 1e6, 'M')
        self.frame_prior_net = FramePriorNet(inter_channels,
                                             hidden_channels,
                                             filter_channels,
                                             n_heads,
                                             n_layers,
                                             kernel_size,
                                             p_dropout)

        self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
                             upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
        self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
                                      gin_channels=gin_channels)
        self.flow = ResidualCouplingBlock(
            inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
        )
        self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)
        vq_dim = 512
        self.prosody_encoder = ProsodyEncoder(768, hidden_channels, 5, 1, 6, gin_channels, vq_dim)
        self.aligner = AlignmentEncoder(
            n_mel_channels=hidden_channels,
            n_att_channels=256,
            n_text_channels=128,
            temperature=0.0005,
            multi_speaker=True,
            spk_channel=gin_channels
        )

        self.prosody_predictor = NARPredictor(vq_dim, gin_channels=gin_channels)

    def forward(self, x, x_lengths, y, y_lengths, ssl, attn_priors, bert, spk_emb, ):
        x_long = x.clone()
        y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype)
        g = self.ref_enc(y * y_mask, y_mask)

        x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype)
        v_mask = (x > 0).float()

        x, x_align = self.enc_p(x, x_mask, bert, g)
        z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)

        attn_out, attn, duration = mono_align_and_get_loss(self.aligner, x_align, z.detach(), x_mask, y_mask, attn_priors, x_lengths, y_lengths, g)

        z_q, quantize_loss, indices, dur_loss, pred_dur = self.prosody_encoder(ssl, x_mask, attn, duration, v_mask)

        prosody_predict_loss = self.prosody_predictor(x_long, x_mask, bert, spk_emb, indices)
        return prosody_predict_loss, indices

    def reconstruct(self, x, x_lengths, y, y_lengths, ssl, bert, spk_emb, noise_scale=.4):
        x_long = x.clone()

        y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype)
        g = self.ref_enc(y * y_mask, y_mask)

        x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype)

        # attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
        # attn = commons.generate_path(duration.unsqueeze(1), attn_mask)
        # v_mask = (x > 0).float()
        # _, _, pred_prosody_codes, _, _ = self.prosody_encoder(ssl, x_mask, attn, duration,v_mask)
        x, x_align = self.enc_p(x, x_mask, bert, g)

        pred_prosody_codes = self.prosody_predictor.infer(x_long, x_mask, bert, spk_emb)


        z_q, duration = self.prosody_encoder.decode(pred_prosody_codes, x_mask)

        total_duration = torch.sum(duration, dim=1)
        y_lengths = total_duration.long()

        y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y_lengths.max()), 1).float()
        attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)

        attn = commons.generate_path(duration.unsqueeze(1), attn_mask)

        x = x + z_q

        frame_x = torch.matmul(attn.squeeze(1), x.transpose(1, 2)).transpose(1, 2)
        m_p, logs_p = self.frame_prior_net(frame_x, y_mask)

        z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
        z = self.flow(z_p, y_mask, g=g, reverse=True)
        o = self.dec((z * y_mask), g=g)
        return o, attn, y_mask, (z, z_p, m_p, logs_p)