File size: 10,094 Bytes
4edc9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import torch
import torch.nn as nn
from einops import pack, rearrange

from .unit_nn import (
    SinusoidalPosEmb,
    TimestepEmbedding,
    ResnetBlock1D,
    Block1D,
)

from .transformer import BasicTransformerBlock


# ---------------------------------------------------------------------------
# Small helpers to keep block construction readable
# ---------------------------------------------------------------------------


def _make_resnet(dim_in, dim_out, time_emb_dim, cond_dim):
    return ResnetBlock1D(
        dim=dim_in,
        dim_out=dim_out,
        time_emb_dim=time_emb_dim,
        film_dim=cond_dim,
    )


def _make_transformer(dim, n_heads, head_dim, dropout, act_fn):
    return BasicTransformerBlock(
        dim=dim,
        num_attention_heads=n_heads,
        attention_head_dim=head_dim,
        dropout=dropout,
        activation_fn=act_fn,
    )


# ---------------------------------------------------------------------------
# Building-block containers
# ---------------------------------------------------------------------------


class DownBlock(nn.Module):
    """
    ResNet -> n Transformer blocks -> channel-mixing Conv1d.
    T is never halved; the conv is purely for channel interaction.
    """

    def __init__(
        self,
        dim_in,
        dim_out,
        time_emb_dim,
        cond_dim,
        n_transformer,
        n_heads,
        head_dim,
        dropout,
        act_fn,
    ):
        super().__init__()
        self.resnet = _make_resnet(dim_in, dim_out, time_emb_dim, cond_dim)
        self.transformers = nn.ModuleList(
            [
                _make_transformer(dim_out, n_heads, head_dim, dropout, act_fn)
                for _ in range(n_transformer)
            ]
        )
        self.mix = nn.Conv1d(dim_out, dim_out, 3, padding=1)

    def forward(self, x, t, cond=None):
        x = self.resnet(x, t, film_cond=cond)
        x = rearrange(x, "b c t -> b t c")
        for block in self.transformers:
            x = block(hidden_states=x, attention_mask=None, timestep=t)
        x = rearrange(x, "b t c -> b c t")
        return self.mix(x)


class MidBlock(nn.Module):
    """ResNet -> n Transformer blocks. No spatial change."""

    def __init__(
        self,
        dim,
        time_emb_dim,
        cond_dim,
        n_transformer,
        n_heads,
        head_dim,
        dropout,
        act_fn,
    ):
        super().__init__()
        self.resnet = _make_resnet(dim, dim, time_emb_dim, cond_dim)
        self.transformers = nn.ModuleList(
            [
                _make_transformer(dim, n_heads, head_dim, dropout, act_fn)
                for _ in range(n_transformer)
            ]
        )

    def forward(self, x, t, cond=None):
        x = self.resnet(x, t, film_cond=cond)
        x = rearrange(x, "b c t -> b t c")
        for block in self.transformers:
            x = block(hidden_states=x, attention_mask=None, timestep=t)
        return rearrange(x, "b t c -> b c t")


class UpBlock(nn.Module):
    """
    Skip-connection concat -> ResNet -> n Transformer blocks -> Conv1d.
    dim_in is the channel dim of the skip, not the doubled dim;
    the doubling is handled internally via ResnetBlock1D(dim=2*dim_in).
    """

    def __init__(
        self,
        dim_in,
        dim_out,
        time_emb_dim,
        cond_dim,
        n_transformer,
        n_heads,
        head_dim,
        dropout,
        act_fn,
    ):
        super().__init__()
        self.resnet = _make_resnet(2 * dim_in, dim_out, time_emb_dim, cond_dim)
        self.transformers = nn.ModuleList(
            [
                _make_transformer(dim_out, n_heads, head_dim, dropout, act_fn)
                for _ in range(n_transformer)
            ]
        )
        self.mix = nn.Conv1d(dim_out, dim_out, 3, padding=1)

    def forward(self, x, skip, t, cond=None):
        x = self.resnet(pack([x, skip], "b * t")[0], t, film_cond=cond)
        x = rearrange(x, "b c t -> b t c")
        for block in self.transformers:
            x = block(hidden_states=x, attention_mask=None, timestep=t)
        x = rearrange(x, "b t c -> b c t")
        return self.mix(x)


# ---------------------------------------------------------------------------
# Full Decoder
# ---------------------------------------------------------------------------


class Decoder(nn.Module):
    """
    1D U-Net decoder for Matcha-TTS CFM.

    Time dimension T is held constant throughout (no spatial downsampling).
    The "U-Net" structure provides multi-scale channel mixing and
    skip connections for gradient flow, not resolution pyramids.

    Input channels to the first block are 2 * in_channels because
    mu is channel-concatenated with x before entering the U-Net.

    Args:
        in_channels:    feat_dim (mel bins or latent dim)
        out_channels:   feat_dim (same; predicts residual vector field)
        channels:       channel widths at each down/up level
        n_mid_blocks:   number of mid blocks at the bottleneck
        n_transformer:  transformer blocks per down/mid/up stage
        n_heads:        attention heads
        head_dim:       dimension per head
        dropout:        dropout in transformers
        act_fn:         activation in transformer FFN ('snake' or 'silu')
        cond_dim:       optional semantic conditioning dim (pooled mu etc.)
    """

    def __init__(
        self,
        in_channels: int = None,
        out_channels: int = None,
        channels: tuple = (256, 256),
        n_mid_blocks: int = 2,
        n_transformer: int = 1,
        n_heads: int = 4,
        head_dim: int = 64,
        dropout: float = 0.05,
        act_fn: str = "snakebeta",
        cond_dim: int = None,
        in_c: int = None,  # TODO need to fix these dumbass details
        out_c: int = None, # TODO need to fix these dumbass details
    ):
        super().__init__()

        if in_channels is None:
            in_channels = in_c
        elif in_c is not None and in_c != in_channels:
            raise ValueError("Received conflicting values for in_channels and in_c.")

        if out_channels is None:
            out_channels = out_c
        elif out_c is not None and out_c != out_channels:
            raise ValueError("Received conflicting values for out_channels and out_c.")

        if in_channels is None or out_channels is None:
            raise ValueError(
                "Decoder requires in_channels/out_channels (or aliases in_c/out_c)."
            )

        # Time conditioning
        time_emb_dim = channels[0] * 4
        self.time_emb = SinusoidalPosEmb(channels[0])
        self.time_mlp = TimestepEmbedding(
            in_channels=channels[0],
            time_embed_dim=time_emb_dim,
            act_fn="silu",
            cond_proj_dim=cond_dim,
        )

        # mu is concatenated into x before the U-Net, so first dim_in = 2 * in_channels
        dims_in = (2 * in_channels,) + channels[:-1]
        dims_out = channels

        self.down_blocks = nn.ModuleList(
            [
                DownBlock(
                    di,
                    do,
                    time_emb_dim,
                    cond_dim,
                    n_transformer,
                    n_heads,
                    head_dim,
                    dropout,
                    act_fn,
                )
                for di, do in zip(dims_in, dims_out)
            ]
        )

        self.mid_blocks = nn.ModuleList(
            [
                MidBlock(
                    channels[-1],
                    time_emb_dim,
                    cond_dim,
                    n_transformer,
                    n_heads,
                    head_dim,
                    dropout,
                    act_fn,
                )
                for _ in range(n_mid_blocks)
            ]
        )

        # Up path: channel dims mirror the down path in reverse
        up_dims_in = channels[::-1]
        up_dims_out = channels[::-1][1:] + (channels[0],)

        self.up_blocks = nn.ModuleList(
            [
                UpBlock(
                    di,
                    do,
                    time_emb_dim,
                    cond_dim,
                    n_transformer,
                    n_heads,
                    head_dim,
                    dropout,
                    act_fn,
                )
                for di, do in zip(up_dims_in, up_dims_out)
            ]
        )

        self.final_block = Block1D(channels[0], channels[0])
        self.final_proj = nn.Conv1d(channels[0], out_channels, 1)

        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, (nn.Conv1d, nn.Linear)):
                nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.GroupNorm):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def forward(
        self,
        x: torch.Tensor,  # (B, feat_dim, T)  noisy interpolant
        mu: torch.Tensor,  # (B, feat_dim, T)  encoder conditioning
        t: torch.Tensor,  # (B,)              flow timestep
        cond: torch.Tensor = None,  # (B, cond_dim)     optional semantic cond
    ) -> torch.Tensor:  # (B, feat_dim, T)

        # Time embedding
        t = t.reshape(x.shape[0])
        t = self.time_mlp(self.time_emb(t), condition=cond)

        # Condition on mu via channel concatenation
        x = pack([x, mu], "b * t")[0]  # (B, 2*feat_dim, T)

        # Down path - save hiddens for skip connections
        hiddens = []
        for block in self.down_blocks:
            x = block(x, t, cond)
            hiddens.append(x)

        # Bottleneck
        for block in self.mid_blocks:
            x = block(x, t, cond)

        # Up path - skip connections from corresponding down blocks
        for block in self.up_blocks:
            x = block(x, hiddens.pop(), t, cond)

        x = self.final_block(x)
        return self.final_proj(x)