unet_grad_tts.py 7.18 KB
Newer Older
patil-suraj's avatar
patil-suraj committed
1
import torch
patil-suraj's avatar
patil-suraj committed
2
from numpy import pad
patil-suraj's avatar
patil-suraj committed
3
4
5

from ..configuration_utils import ConfigMixin
from ..modeling_utils import ModelMixin
6
from .embeddings import get_timestep_embedding
patil-suraj's avatar
patil-suraj committed
7
from .resnet import Downsample, Upsample
Patrick von Platen's avatar
Patrick von Platen committed
8
from .attention2d import LinearAttention
patil-suraj's avatar
patil-suraj committed
9

10

patil-suraj's avatar
patil-suraj committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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__()
29
30
31
        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
32
33
34
35
36
37
38
39
40

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


class ResnetBlock(torch.nn.Module):
    def __init__(self, dim, dim_out, time_emb_dim, groups=8):
        super(ResnetBlock, self).__init__()
41
        self.mlp = torch.nn.Sequential(Mish(), torch.nn.Linear(time_emb_dim, dim_out))
patil-suraj's avatar
patil-suraj committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

        self.block1 = Block(dim, dim_out, groups=groups)
        self.block2 = Block(dim_out, dim_out, groups=groups)
        if dim != dim_out:
            self.res_conv = torch.nn.Conv2d(dim, dim_out, 1)
        else:
            self.res_conv = torch.nn.Identity()

    def forward(self, x, mask, time_emb):
        h = self.block1(x, mask)
        h += self.mlp(time_emb).unsqueeze(-1).unsqueeze(-1)
        h = self.block2(h, mask)
        output = h + self.res_conv(x * mask)
        return output


Patrick von Platen's avatar
Patrick von Platen committed
58
class old_LinearAttention(torch.nn.Module):
patil-suraj's avatar
patil-suraj committed
59
60
61
    def __init__(self, dim, heads=4, dim_head=32):
        super(LinearAttention, self).__init__()
        self.heads = heads
Patrick von Platen's avatar
Patrick von Platen committed
62
        self.dim_head = dim_head
patil-suraj's avatar
patil-suraj committed
63
64
        hidden_dim = dim_head * heads
        self.to_qkv = torch.nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
65
        self.to_out = torch.nn.Conv2d(hidden_dim, dim, 1)
patil-suraj's avatar
patil-suraj committed
66
67
68
69

    def forward(self, x):
        b, c, h, w = x.shape
        qkv = self.to_qkv(x)
Patrick von Platen's avatar
Patrick von Platen committed
70
71
72
73
74
75
        #        q, k, v = rearrange(qkv, "b (qkv heads c) h w -> qkv b heads c (h w)", heads=self.heads, qkv=3)
        q, k, v = (
            qkv.reshape(b, 3, self.heads, self.dim_head, h, w)
            .permute(1, 0, 2, 3, 4, 5)
            .reshape(3, b, self.heads, self.dim_head, -1)
        )
patil-suraj's avatar
patil-suraj committed
76
        k = k.softmax(dim=-1)
77
78
        context = torch.einsum("bhdn,bhen->bhde", k, v)
        out = torch.einsum("bhde,bhdn->bhen", context, q)
Patrick von Platen's avatar
Patrick von Platen committed
79
80
        #        out = rearrange(out, "b heads c (h w) -> b (heads c) h w", heads=self.heads, h=h, w=w)
        out = out.reshape(b, self.heads, self.dim_head, h, w).reshape(b, self.heads * self.dim_head, h, w)
patil-suraj's avatar
patil-suraj committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        return self.to_out(out)


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):
95
    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
96
97
        super(UNetGradTTSModel, self).__init__()

98
        self.register_to_config(
patil-suraj's avatar
patil-suraj committed
99
100
101
102
103
104
            dim=dim,
            dim_mults=dim_mults,
            groups=groups,
            n_spks=n_spks,
            spk_emb_dim=spk_emb_dim,
            n_feats=n_feats,
105
            pe_scale=pe_scale,
patil-suraj's avatar
patil-suraj committed
106
        )
107

patil-suraj's avatar
patil-suraj committed
108
109
110
111
112
113
        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
114

patil-suraj's avatar
patil-suraj committed
115
        if n_spks > 1:
patil-suraj's avatar
patil-suraj committed
116
            self.spk_emb = torch.nn.Embedding(n_spks, spk_emb_dim)
patil-suraj's avatar
style  
patil-suraj committed
117
118
119
            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)
            )
120

121
        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
122
123
124
125
126
127
128
129
130

        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)

        for ind, (dim_in, dim_out) in enumerate(in_out):
            is_last = ind >= (num_resolutions - 1)
131
132
133
134
135
136
            self.downs.append(
                torch.nn.ModuleList(
                    [
                        ResnetBlock(dim_in, dim_out, time_emb_dim=dim),
                        ResnetBlock(dim_out, dim_out, time_emb_dim=dim),
                        Residual(Rezero(LinearAttention(dim_out))),
patil-suraj's avatar
patil-suraj committed
137
                        Downsample(dim_out, use_conv=True, padding=1) if not is_last else torch.nn.Identity(),
138
139
140
                    ]
                )
            )
patil-suraj's avatar
patil-suraj committed
141
142
143
144
145
146
147

        mid_dim = dims[-1]
        self.mid_block1 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)
        self.mid_attn = Residual(Rezero(LinearAttention(mid_dim)))
        self.mid_block2 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)

        for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
148
149
150
151
152
153
            self.ups.append(
                torch.nn.ModuleList(
                    [
                        ResnetBlock(dim_out * 2, dim_in, time_emb_dim=dim),
                        ResnetBlock(dim_in, dim_in, time_emb_dim=dim),
                        Residual(Rezero(LinearAttention(dim_in))),
patil-suraj's avatar
patil-suraj committed
154
                        Upsample(dim_in, use_conv_transpose=True),
155
156
157
                    ]
                )
            )
patil-suraj's avatar
patil-suraj committed
158
159
160
        self.final_block = Block(dim, dim)
        self.final_conv = torch.nn.Conv2d(dim, 1, 1)

patil-suraj's avatar
patil-suraj committed
161
    def forward(self, x, timesteps, mu, mask, spk=None):
patil-suraj's avatar
patil-suraj committed
162
163
164
165
        if self.n_spks > 1:
            # Get speaker embedding
            spk = self.spk_emb(spk)

patil-suraj's avatar
patil-suraj committed
166
167
        if not isinstance(spk, type(None)):
            s = self.spk_mlp(spk)
168

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

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