unet_grad_tts.py 6.66 KB
Newer Older
patil-suraj's avatar
patil-suraj committed
1
2
3
4
import torch

from ..configuration_utils import ConfigMixin
from ..modeling_utils import ModelMixin
Patrick von Platen's avatar
Patrick von Platen committed
5
from .attention import LinearAttention
6
from .embeddings import get_timestep_embedding
Patrick von Platen's avatar
Patrick von Platen committed
7
from .resnet import Downsample
8
from .resnet import ResnetBlock as ResnetBlockNew
Patrick von Platen's avatar
Patrick von Platen committed
9
10
from .resnet import ResnetBlockGradTTS as ResnetBlock
from .resnet import Upsample
patil-suraj's avatar
patil-suraj committed
11

12

patil-suraj's avatar
patil-suraj committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Mish(torch.nn.Module):
    def forward(self, x):
        return x * torch.tanh(torch.nn.functional.softplus(x))


class Rezero(torch.nn.Module):
    def __init__(self, fn):
        super(Rezero, self).__init__()
        self.fn = fn
        self.g = torch.nn.Parameter(torch.zeros(1))

    def forward(self, x):
        return self.fn(x) * self.g


class Block(torch.nn.Module):
    def __init__(self, dim, dim_out, groups=8):
        super(Block, self).__init__()
31
32
33
        self.block = torch.nn.Sequential(
            torch.nn.Conv2d(dim, dim_out, 3, padding=1), torch.nn.GroupNorm(groups, dim_out), Mish()
        )
patil-suraj's avatar
patil-suraj committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

    def forward(self, x, mask):
        output = self.block(x * mask)
        return output * mask


class Residual(torch.nn.Module):
    def __init__(self, fn):
        super(Residual, self).__init__()
        self.fn = fn

    def forward(self, x, *args, **kwargs):
        output = self.fn(x, *args, **kwargs) + x
        return output


class UNetGradTTSModel(ModelMixin, ConfigMixin):
51
    def __init__(self, dim, dim_mults=(1, 2, 4), groups=8, n_spks=None, spk_emb_dim=64, n_feats=80, pe_scale=1000):
patil-suraj's avatar
patil-suraj committed
52
53
        super(UNetGradTTSModel, self).__init__()

54
        self.register_to_config(
patil-suraj's avatar
patil-suraj committed
55
56
57
58
59
60
            dim=dim,
            dim_mults=dim_mults,
            groups=groups,
            n_spks=n_spks,
            spk_emb_dim=spk_emb_dim,
            n_feats=n_feats,
61
            pe_scale=pe_scale,
patil-suraj's avatar
patil-suraj committed
62
        )
63

patil-suraj's avatar
patil-suraj committed
64
65
66
67
68
69
        self.dim = dim
        self.dim_mults = dim_mults
        self.groups = groups
        self.n_spks = n_spks if not isinstance(n_spks, type(None)) else 1
        self.spk_emb_dim = spk_emb_dim
        self.pe_scale = pe_scale
70

patil-suraj's avatar
patil-suraj committed
71
        if n_spks > 1:
patil-suraj's avatar
patil-suraj committed
72
            self.spk_emb = torch.nn.Embedding(n_spks, spk_emb_dim)
patil-suraj's avatar
style  
patil-suraj committed
73
74
75
            self.spk_mlp = torch.nn.Sequential(
                torch.nn.Linear(spk_emb_dim, spk_emb_dim * 4), Mish(), torch.nn.Linear(spk_emb_dim * 4, n_feats)
            )
76

77
        self.mlp = torch.nn.Sequential(torch.nn.Linear(dim, dim * 4), Mish(), torch.nn.Linear(dim * 4, dim))
patil-suraj's avatar
patil-suraj committed
78
79
80
81
82
83
84

        dims = [2 + (1 if n_spks > 1 else 0), *map(lambda m: dim * m, dim_mults)]
        in_out = list(zip(dims[:-1], dims[1:]))
        self.downs = torch.nn.ModuleList([])
        self.ups = torch.nn.ModuleList([])
        num_resolutions = len(in_out)

85
86
87
88
89
#        num_groups = 8
#        self.pre_norm = False
#        eps = 1e-5
#        non_linearity = "mish"

patil-suraj's avatar
patil-suraj committed
90
91
        for ind, (dim_in, dim_out) in enumerate(in_out):
            is_last = ind >= (num_resolutions - 1)
92
93
94
            self.downs.append(
                torch.nn.ModuleList(
                    [
95
96
97
98
#                        ResnetBlock(dim_in, dim_out, time_emb_dim=dim),
#                        ResnetBlock(dim_out, dim_out, time_emb_dim=dim),
                        ResnetBlockNew(in_channels=dim_in, out_channels=dim_out, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True),
                        ResnetBlockNew(in_channels=dim_out, out_channels=dim_out, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True),
99
                        Residual(Rezero(LinearAttention(dim_out))),
patil-suraj's avatar
patil-suraj committed
100
                        Downsample(dim_out, use_conv=True, padding=1) if not is_last else torch.nn.Identity(),
101
102
103
                    ]
                )
            )
patil-suraj's avatar
patil-suraj committed
104
105

        mid_dim = dims[-1]
106
107
108
#        self.mid_block1 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)
#        self.mid_block2 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)
        self.mid_block1 = ResnetBlockNew(in_channels=mid_dim, out_channels=mid_dim, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True)
patil-suraj's avatar
patil-suraj committed
109
        self.mid_attn = Residual(Rezero(LinearAttention(mid_dim)))
110
        self.mid_block2 = ResnetBlockNew(in_channels=mid_dim, out_channels=mid_dim, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True)
patil-suraj's avatar
patil-suraj committed
111
112

        for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
113
114
115
            self.ups.append(
                torch.nn.ModuleList(
                    [
116
117
118
119
#                        ResnetBlock(dim_out * 2, dim_in, time_emb_dim=dim),
#                        ResnetBlock(dim_in, dim_in, time_emb_dim=dim),
                        ResnetBlockNew(in_channels=dim_out * 2, out_channels=dim_in, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True),
                        ResnetBlockNew(in_channels=dim_in, out_channels=dim_in, temb_channels=dim, groups=8, pre_norm=False, eps=1e-5, non_linearity="mish", overwrite_for_grad_tts=True),
120
                        Residual(Rezero(LinearAttention(dim_in))),
patil-suraj's avatar
patil-suraj committed
121
                        Upsample(dim_in, use_conv_transpose=True),
122
123
124
                    ]
                )
            )
patil-suraj's avatar
patil-suraj committed
125
126
127
        self.final_block = Block(dim, dim)
        self.final_conv = torch.nn.Conv2d(dim, 1, 1)

patil-suraj's avatar
patil-suraj committed
128
    def forward(self, x, timesteps, mu, mask, spk=None):
patil-suraj's avatar
patil-suraj committed
129
130
131
132
        if self.n_spks > 1:
            # Get speaker embedding
            spk = self.spk_emb(spk)

patil-suraj's avatar
patil-suraj committed
133
134
        if not isinstance(spk, type(None)):
            s = self.spk_mlp(spk)
135

136
        t = get_timestep_embedding(timesteps, self.dim, scale=self.pe_scale)
patil-suraj's avatar
patil-suraj committed
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
        t = self.mlp(t)

        if self.n_spks < 2:
            x = torch.stack([mu, x], 1)
        else:
            s = s.unsqueeze(-1).repeat(1, 1, x.shape[-1])
            x = torch.stack([mu, x, s], 1)
        mask = mask.unsqueeze(1)

        hiddens = []
        masks = [mask]
        for resnet1, resnet2, attn, downsample in self.downs:
            mask_down = masks[-1]
            x = resnet1(x, mask_down, t)
            x = resnet2(x, mask_down, t)
            x = attn(x)
            hiddens.append(x)
            x = downsample(x * mask_down)
            masks.append(mask_down[:, :, :, ::2])

        masks = masks[:-1]
        mask_mid = masks[-1]
        x = self.mid_block1(x, mask_mid, t)
        x = self.mid_attn(x)
        x = self.mid_block2(x, mask_mid, t)

        for resnet1, resnet2, attn, upsample in self.ups:
            mask_up = masks.pop()
            x = torch.cat((x, hiddens.pop()), dim=1)
            x = resnet1(x, mask_up, t)
            x = resnet2(x, mask_up, t)
            x = attn(x)
            x = upsample(x * mask_up)

        x = self.final_block(x, mask)
        output = self.final_conv(x * mask)

174
        return (output * mask).squeeze(1)