File size: 7,537 Bytes
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
870eedf
 
 
 
8d10455
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
8d10455
42e63f8
870eedf
 
 
 
 
 
 
 
8d10455
 
870eedf
 
 
42e63f8
 
 
 
870eedf
 
 
8d10455
 
42e63f8
 
 
 
 
 
 
 
 
 
 
 
 
870eedf
42e63f8
 
 
 
870eedf
 
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
"""
Murli V1.6 2026 Hybrid ConvNeXt-V2 + RoPE DiT Self-Attention OT-CFM Vector Field (AdaLN-Zero).
Combines local ConvNeXt harmonic sharpness with global RoPE Self-Attention sentence prosody arcs,
explicitly conditioned on timestep t + SpeakerEmbedding via zero-gated AdaLN-Zero.
100% opset-17 Android ONNX Runtime Mobile compatible.
"""

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

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


class AdaLNZeroDiTBlock(nn.Module):
    """Global RoPE Self-Attention + SwiGLU DiT block modulated via AdaLN-Zero."""

    def __init__(self, dim: int, num_heads: int = 6, ff_mult: float = 2.0):
        super().__init__()
        self.norm1 = RMSNorm(dim)
        self.attn = MultiHeadSDPA(dim, num_heads=num_heads, use_rope=True)
        self.norm2 = RMSNorm(dim)
        self.mlp = SwiGLU(dim, ff_mult=ff_mult)
        self.ada_proj = nn.Sequential(
            nn.SiLU(),
            nn.Linear(dim, dim * 6),
        )
        nn.init.zeros_(self.ada_proj[1].weight)
        nn.init.zeros_(self.ada_proj[1].bias)

    def forward(self, x: torch.Tensor, c_emb: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        shift1, scale1, gate1, shift2, scale2, gate2 = self.ada_proj(c_emb).unsqueeze(1).chunk(6, dim=-1)
        h1 = self.norm1(x) * (1.0 + scale1) + shift1
        x = x + gate1 * self.attn(h1, key_padding_mask=mask)
        h2 = self.norm2(x) * (1.0 + scale2) + shift2
        x = x + gate2 * self.mlp(h2)
        if mask is not None:
            x = x * mask.unsqueeze(-1).to(x.dtype)
        return x


class HybridDiTCFMVectorField(nn.Module):
    """2026 Hybrid ConvNeXt-V2 + AdaLN-Zero RoPE DiT OT-CFM Vector Field."""

    def __init__(
        self,
        mel_dim: int = 100,
        cond_dim: int = 320,
        hidden_dim: int = 384,
        num_blocks: int = 12,
        kernel_size: int = 7,
        attn_heads: int = 6,
        attn_every: int = 3,
        time_dim: int = 128,
        num_speakers: int = 4,
    ):
        super().__init__()
        self.mel_dim = mel_dim
        self.cond_dim = cond_dim
        self.hidden_dim = hidden_dim
        self.attn_every = attn_every

        self.time_embed = nn.Sequential(
            SinusoidalTimestepEmbed(time_dim),
            nn.Linear(time_dim, hidden_dim),
            nn.SiLU(),
            nn.Linear(hidden_dim, hidden_dim),
        )
        self.speaker_emb = nn.Embedding(num_speakers, hidden_dim)
        self.in_proj = nn.Conv1d(mel_dim + cond_dim, hidden_dim, kernel_size=1)

        self.blocks = nn.ModuleList([
            ConvNeXt1DBlock(hidden_dim, kernel_size=kernel_size, mult=3)
            for _ in range(num_blocks)
        ])
        # AdaLN scale+shift conditioning per ConvNeXt block (zero-initialized for identity start)
        self.conv_ada = nn.ModuleList([
            nn.Linear(hidden_dim, hidden_dim * 2)
            for _ in range(num_blocks)
        ])
        for ada in self.conv_ada:
            nn.init.zeros_(ada.weight)
            nn.init.zeros_(ada.bias)
        self.dit_blocks = nn.ModuleList([
            AdaLNZeroDiTBlock(hidden_dim, num_heads=attn_heads, ff_mult=2.0)
            if ((idx + 1) % attn_every == 0) else nn.Identity()
            for idx in range(num_blocks)
        ])
        self.final_norm = RMSNorm(hidden_dim)
        self.out_proj = nn.Conv1d(hidden_dim, mel_dim, kernel_size=1)

    def forward(
        self,
        x: torch.Tensor,
        t: torch.Tensor,
        cond: torch.Tensor,
        speaker_ids: Optional[torch.Tensor] = None,
        mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if speaker_ids is None:
            speaker_ids = torch.zeros((x.shape[0],), dtype=torch.long, device=x.device)
        c_emb = self.time_embed(t) + self.speaker_emb(speaker_ids)  # [B, hidden_dim]
        h = self.in_proj(torch.cat([x, cond], dim=1)).transpose(1, 2)  # [B, T_mel, hidden_dim]

        for blk, ada, dit in zip(self.blocks, self.conv_ada, self.dit_blocks):
            shift, scale = ada(c_emb).unsqueeze(1).chunk(2, dim=-1)
            h = blk(h * (1.0 + scale) + shift, mask=mask)
            if not isinstance(dit, nn.Identity):
                h = dit(h, c_emb, mask=mask)

        h = self.final_norm(h).transpose(1, 2)
        out = self.out_proj(h)
        if mask is not None:
            out = out * mask.unsqueeze(1).to(out.dtype)
        return out


def compute_cfm_loss(
    vector_field: HybridDiTCFMVectorField,
    mel_target: torch.Tensor,
    cond: torch.Tensor,
    mel_mask: torch.Tensor,
    speaker_ids: torch.Tensor,
    cfg_drop_prob: float = 0.1,
    sigma_min: float = 1e-4,
) -> torch.Tensor:
    bsz, _, _ = mel_target.shape
    device = mel_target.device

    if cfg_drop_prob > 0.0:
        keep = (torch.rand(bsz, 1, 1, device=device) >= cfg_drop_prob).to(cond.dtype)
        cond_in = cond * keep
    else:
        cond_in = cond

    t = torch.rand(bsz, device=device, dtype=mel_target.dtype)
    x0 = torch.randn_like(mel_target)
    t_3d = t.view(bsz, 1, 1)

    xt = (1.0 - (1.0 - sigma_min) * t_3d) * x0 + t_3d * mel_target
    target_v = mel_target - (1.0 - sigma_min) * x0

    pred_v = vector_field(xt, t, cond_in, speaker_ids=speaker_ids, mask=mel_mask)
    mask_3d = mel_mask.unsqueeze(1).float()
    return F.mse_loss(pred_v * mask_3d, target_v * mask_3d, reduction="sum") / (
        mask_3d.sum() * mel_target.shape[1] + 1e-6
    )


@torch.no_grad()
def sample_ode(
    vector_field: HybridDiTCFMVectorField,
    cond: torch.Tensor,
    speaker_ids: Optional[torch.Tensor] = None,
    steps: int = 48,
    cfg_scale: float = 1.3,
    temperature: float = 0.90,
    mask: Optional[torch.Tensor] = None,
    solver: str = "midpoint",
) -> torch.Tensor:
    bsz, _, t_mel = cond.shape
    device = cond.device
    dtype = cond.dtype
    if speaker_ids is None:
        speaker_ids = torch.zeros((bsz,), dtype=torch.long, device=device)

    x = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperature
    if mask is not None:
        x = x * mask.unsqueeze(1).to(dtype)
    dt = 1.0 / float(steps)
    null_cond = torch.zeros_like(cond)

    def _velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
        t_cur = torch.full((bsz,), t_val, device=device, dtype=dtype)
        if cfg_scale != 1.0:
            x_in = torch.cat([x_cur, x_cur], dim=0)
            t_in = torch.cat([t_cur, t_cur], dim=0)
            c_in = torch.cat([cond, null_cond], dim=0)
            s_in = torch.cat([speaker_ids, speaker_ids], dim=0)
            m_in = torch.cat([mask, mask], dim=0) if mask is not None else None
            v_cond, v_uncond = vector_field(x_in, t_in, c_in, speaker_ids=s_in, mask=m_in).chunk(2, dim=0)
            return v_uncond + cfg_scale * (v_cond - v_uncond)
        return vector_field(x_cur, t_cur, cond, speaker_ids=speaker_ids, mask=mask)

    for i in range(steps):
        t0 = float(i) * dt
        v1 = _velocity(x, t0)
        if solver == "midpoint":
            x_mid = x + 0.5 * dt * v1
            if mask is not None:
                x_mid = x_mid * mask.unsqueeze(1).to(dtype)
            v_step = _velocity(x_mid, t0 + 0.5 * dt)
        elif solver == "euler":
            v_step = v1
        else:
            raise ValueError(f"Unknown ODE solver: {solver!r}")
        x = x + v_step * dt
        if mask is not None:
            x = x * mask.unsqueeze(1).to(dtype)

    return x