File size: 5,075 Bytes
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Murli V2.0 — 2026 Diffusion Transformer (DiT) Vector Field for OT-CFM.
Features AdaLN-Zero conditioning (Flow time t + Zero-Shot Global Speaker),
RoPE Self-Attention, Cross-Attention to Perceiver Style Tokens, SwiGLU MLP,
and Explicit Frame-Level Text + Pitch (F0) + Energy Injection.
"""

from typing import Optional
import torch
import torch.nn as nn

from models.layers import MultiHeadSDPA, RMSNorm, SinusoidalTimestepEmbed, SwiGLU


def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
    return x * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)


class DiTBlock(nn.Module):
    """Single 2026 AdaLN-Zero Diffusion Transformer block with Style Cross-Attention."""

    def __init__(self, dim: int, style_dim: int, num_heads: int, ff_mult: float = 2.667, dropout: float = 0.05):
        super().__init__()
        self.norm1 = RMSNorm(dim)
        self.self_attn = MultiHeadSDPA(dim, num_heads, dropout=dropout, use_rope=True)

        self.norm_cross = RMSNorm(dim)
        self.style_cross_attn = MultiHeadSDPA(dim, num_heads, kv_dim=style_dim, dropout=dropout, use_rope=False)

        self.norm2 = RMSNorm(dim)
        self.mlp = SwiGLU(dim, ff_mult=ff_mult, dropout=dropout)

        # AdaLN-Zero modulation: shift1, scale1, gate1, shift2, scale2, gate2
        self.ada_ln = nn.Sequential(
            nn.SiLU(),
            nn.Linear(dim, dim * 6),
        )
        nn.init.zeros_(self.ada_ln[-1].weight)
        nn.init.zeros_(self.ada_ln[-1].bias)

    def forward(
        self,
        x: torch.Tensor,
        cond_emb: torch.Tensor,
        style_tokens: torch.Tensor,
        mel_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        shift1, scale1, gate1, shift2, scale2, gate2 = self.ada_ln(cond_emb).chunk(6, dim=-1)

        # 1. RoPE Self-Attention modulated by time + speaker embedding
        h = modulate(self.norm1(x), shift1, scale1)
        x = x + gate1.unsqueeze(1) * self.self_attn(h, key_padding_mask=mel_mask)

        # 2. Cross-Attention into Perceiver Zero-Shot Style Latents
        x = x + self.style_cross_attn(self.norm_cross(x), kv=style_tokens)

        # 3. AdaLN-Zero SwiGLU MLP
        h2 = modulate(self.norm2(x), shift2, scale2)
        x = x + gate2.unsqueeze(1) * self.mlp(h2)

        if mel_mask is not None:
            x = x * mel_mask.unsqueeze(-1).to(x.dtype)
        return x


class DiTVectorField(nn.Module):
    """Predicts Optimal Transport velocity v_theta(x_t, t | text, prior, f0, energy, style)."""

    def __init__(
        self,
        n_mels: int = 100,
        text_dim: int = 384,
        style_dim: int = 384,
        dit_dim: int = 512,
        num_layers: int = 8,
        num_heads: int = 8,
        ff_mult: float = 2.667,
        dropout: float = 0.05,
    ):
        super().__init__()
        self.n_mels = n_mels
        self.dit_dim = dit_dim

        # Concatenate noisy mel x_t, mel prior mu, aligned text, pitch (F0), energy
        in_ch = n_mels + n_mels + text_dim + 2
        self.in_proj = nn.Linear(in_ch, dit_dim)

        self.time_embed = SinusoidalTimestepEmbed(dit_dim)
        self.style_global_proj = nn.Sequential(
            nn.Linear(style_dim, dit_dim),
            nn.SiLU(),
            nn.Linear(dit_dim, dit_dim),
        )

        self.blocks = nn.ModuleList([
            DiTBlock(dit_dim, style_dim=style_dim, num_heads=num_heads, ff_mult=ff_mult, dropout=dropout)
            for _ in range(num_layers)
        ])

        self.final_norm = RMSNorm(dit_dim)
        self.final_ada = nn.Sequential(
            nn.SiLU(),
            nn.Linear(dit_dim, dit_dim * 2),
        )
        nn.init.zeros_(self.final_ada[-1].weight)
        nn.init.zeros_(self.final_ada[-1].bias)
        self.out_proj = nn.Linear(dit_dim, n_mels)

    def forward(
        self,
        x_t: torch.Tensor,
        t: torch.Tensor,
        aligned_text: torch.Tensor,
        aligned_prior: torch.Tensor,
        f0: torch.Tensor,
        energy: torch.Tensor,
        style_tokens: torch.Tensor,
        style_global: torch.Tensor,
        mel_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """
        x_t, aligned_prior: [B, M, T]
        aligned_text: [B, T, D_text]
        f0, energy: [B, T]
        """
        feats = torch.cat(
            [
                x_t.transpose(1, 2),
                aligned_prior.transpose(1, 2),
                aligned_text,
                f0.unsqueeze(-1),
                energy.unsqueeze(-1),
            ],
            dim=-1,
        )
        h = self.in_proj(feats)
        cond_emb = self.time_embed(t) + self.style_global_proj(style_global)

        for blk in self.blocks:
            h = blk(h, cond_emb=cond_emb, style_tokens=style_tokens, mel_mask=mel_mask)

        shift, scale = self.final_ada(cond_emb).chunk(2, dim=-1)
        h = modulate(self.final_norm(h), shift, scale)
        vel = self.out_proj(h).transpose(1, 2)  # [B, M, T]
        if mel_mask is not None:
            vel = vel * mel_mask.unsqueeze(1).to(vel.dtype)
        return vel