File size: 9,468 Bytes
138fdcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
from module import commons
from module import modules



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):
        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)
        x = self.position(x)
        x, _ = self.encoder(
            (x, None), src_key_padding_mask=None)
        x = x[:, 1:, :]
        x = self.proj(x).transpose(1, 2)
        return x

from .edm import EDM2NetworkWrapper, edm_sampler

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

        self.latent_dim = latent_dim
        self.bert_proj = nn.Linear(1024, 192)
        # self.x_proj = nn.Linear(192, 192)
        self.g_emb = nn.Linear(256, 192)

        self.text_emb = nn.Embedding(len(symbols), 192)


        cond_channels = 192
        net = DiT(latent_dim, cond_channels)
        self.edm_net = EDM2NetworkWrapper(net, use_fp16=False)


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

        cond = (x + bert + g).transpose(1, 2)


        cfg_dropout_prob = 0.1
        null_embed = torch.zeros_like(cond, device=cond.device)
        dropout_mask = torch.bernoulli(torch.full((cond.shape[0], 1, 1), cfg_dropout_prob, device=cond.device)).to(torch.bool)
        cond = torch.where(dropout_mask, null_embed, cond)



        P_std = 1.0
        P_mean = -0.4
        sigma_data = 0.4


        rnd_normal = torch.randn([diffusion_input.shape[0], 1, 1], device=diffusion_input.device)
        sigma = (rnd_normal * P_std + P_mean).exp()
        weight = (sigma ** 2 + sigma_data ** 2) / (sigma * sigma_data) ** 2
        noise = torch.randn_like(diffusion_input) * sigma
        denoised, logvar = self.edm_net(diffusion_input + noise, sigma, cond=cond, return_logvar=True)
        loss = (weight / logvar.exp()) * ((denoised - diffusion_input) ** 2) + logvar
        loss = loss.mean()

        return loss

    @torch.inference_mode()
    @torch.no_grad()
    def infer(self, x, x_mask, bert, spk_emb, step=32):

        g = self.g_emb(spk_emb).unsqueeze(1)
        bert = self.bert_proj(bert.transpose(1, 2))
        x = self.text_emb(x)
        cond = (x + bert + g).transpose(1, 2)


        noise = torch.randn([cond.shape[0], self.latent_dim, cond.shape[2]]).to(cond.device)

        fakes = edm_sampler(self.edm_net, noise, cond, num_steps=step, guidance=1.7)


        return fakes


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 = 4
        self.prosody_encoder = ProsodyEncoder(768, hidden_channels, 5, 1, 6, gin_channels, vq_dim)
        self.prosody_predictor = NARPredictor(vq_dim, gin_channels=gin_channels)

    def forward(self, x, x_lengths, y, y_lengths, ssl, duration, bert, spk_emb, prosody_predict_only=False):
        y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype)
        text_long = x.clone()
        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()
        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, x_mask, bert, spk_emb, indices)
        return prosody_predict_loss, indices

    def reconstruct(self, x, x_lengths, y, y_lengths, ssl, duration, bert, spk_emb, noise_scale=.4):
        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)

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

        x = self.enc_p(x, x_mask, bert)

        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)