Murli-V1.6-Code / models /prosody_aligner.py
ViuAI's picture
Murli V1.6 Audited Release (6/6 tests passing): EMA, FP32 CFM mask, F0 autocorr fix, cache & resume hardening
42e63f8 verified
Raw History Blame Contribute Delete
12.5 kB
"""
Murli V1.6 Alignment, Duration, Smooth Frame-Level F0 Pitch & Energy, and ConvNeXt Mel Prior.
Fixes V1.5's flat token-constant pitch staircase via a frame-level prosody refinement net,
and cleanly separates 3 studio voices (2 Male + 1 Female) via SpeakerEmbedding.
"""
from typing import Dict, Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.layers import ConvNeXt1DBlock
try:
from numba import njit, prange
except ImportError:
njit = None
prange = range
if njit is not None:
@njit(parallel=True, cache=True)
def _mas_batch_numba(path, val_np, t_xs, t_ys):
for b in prange(val_np.shape[0]):
tx = t_xs[b]
ty = t_ys[b]
q = np.full((tx, ty), -np.inf, dtype=np.float32)
q[0, 0] = val_np[b, 0, 0]
for y in range(1, ty):
lo = max(0, tx - (ty - y))
hi = min(tx, y + 1)
for x in range(lo, hi):
best = q[x, y - 1]
if x > 0 and q[x - 1, y - 1] > best:
best = q[x - 1, y - 1]
q[x, y] = best + val_np[b, x, y]
x_cur = tx - 1
for y in range(ty - 1, -1, -1):
path[b, x_cur, y] = 1.0
if x_cur > 0 and y > 0 and q[x_cur - 1, y - 1] >= q[x_cur, y - 1]:
x_cur -= 1
else:
_mas_batch_numba = None
def maximum_path(value: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Monotonic Alignment Search (MAS) strictly in FP32."""
return _maximum_path_lengths(value, mask[:, :, 0].bool().sum(1), mask[:, 0, :].bool().sum(1))
def _maximum_path_lengths(value, text_lengths, mel_lengths):
bsz = value.size(0)
val_np = value.detach().float().cpu().numpy()
path = np.zeros_like(val_np, dtype=np.float32)
t_xs, t_ys = torch.stack((text_lengths, mel_lengths)).long().cpu().numpy()
if np.any(t_xs <= 0) or np.any(t_ys <= 0) or np.any(t_xs > t_ys):
raise ValueError("Each sample needs at least one token and at least one mel frame per token")
if _mas_batch_numba is not None:
_mas_batch_numba(path, val_np, t_xs, t_ys)
else:
for b in range(bsz):
tx, ty = int(t_xs[b]), int(t_ys[b])
v = val_np[b, :tx, :ty]
q = np.full((tx, ty), -np.inf, dtype=np.float32)
q[0, 0] = v[0, 0]
for y in range(1, ty):
lo, hi = max(0, tx - (ty - y)), min(tx, y + 1)
stay = q[lo:hi, y - 1].copy()
first_step = max(lo, 1)
stay[first_step - lo :] = np.maximum(stay[first_step - lo :], q[first_step - 1 : hi - 1, y - 1])
q[lo:hi, y] = stay + v[lo:hi, y]
x_cur = tx - 1
for y in range(ty - 1, -1, -1):
path[b, x_cur, y] = 1.0
if x_cur > 0 and y > 0 and q[x_cur - 1, y - 1] >= q[x_cur, y - 1]:
x_cur -= 1
return torch.from_numpy(path).to(value.device)
def expand_by_durations(hidden: torch.Tensor, durations: torch.Tensor, max_len: Optional[int] = None) -> torch.Tensor:
"""Expand [B, T_text, D] into [B, T_mel, D] using integer durations [B, T_text]."""
bsz, _, dim = hidden.shape
d_int = durations.long().clamp(min=0)
lengths = d_int.sum(dim=1)
t_mel = max_len if max_len is not None else int(lengths.max().item())
out = hidden.new_zeros(bsz, t_mel, dim)
for b in range(bsz):
expanded = torch.repeat_interleave(hidden[b], d_int[b], dim=0)
keep = min(expanded.shape[0], t_mel)
if keep > 0:
out[b, :keep] = expanded[:keep]
return out
class ScalarPredictor(nn.Module):
"""ConvNeXt-V2 predictor for Duration, Log-F0 Pitch, and Energy."""
def __init__(self, dim: int, kernel_size: int = 5, num_layers: int = 3):
super().__init__()
self.blocks = nn.ModuleList([ConvNeXt1DBlock(dim, kernel_size=kernel_size, mult=2) for _ in range(num_layers)])
self.head = nn.Linear(dim, 1)
def forward(self, x: torch.Tensor, cond_emb: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
h = x + cond_emb.unsqueeze(1)
for blk in self.blocks:
h = blk(h, mask=mask)
out = self.head(h).squeeze(-1)
if mask is not None:
out = out * mask.to(out.dtype)
return out
class FrameProsodyRefiner(nn.Module):
"""Smooths expanded token F0/Energy into continuous frame-level pitch & energy contours."""
def __init__(self, dim: int, kernel_size: int = 5):
super().__init__()
self.blocks = nn.ModuleList([ConvNeXt1DBlock(dim, kernel_size=kernel_size, mult=2) for _ in range(2)])
self.head = nn.Linear(dim, 2)
nn.init.zeros_(self.head.weight)
nn.init.zeros_(self.head.bias)
def forward(
self,
expanded_h: torch.Tensor,
coarse_prosody: torch.Tensor,
prosody_proj: nn.Linear,
mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
h = expanded_h + prosody_proj(coarse_prosody)
for blk in self.blocks:
h = blk(h, mask=mask)
refined = coarse_prosody + self.head(h)
if mask is not None:
refined = refined * mask.unsqueeze(-1).to(refined.dtype)
return refined
class ProsodyAndAlignmentModule(nn.Module):
"""
Multi-speaker Expressive Prosody + Alignment module:
- SpeakerEmbedding (0=SYSPIN Male, 1=Rasa Male, 2=IISc Female) + EmotionEmbedding
- ConvNeXt Mel Prior + FP32 MAS
- Token Duration / F0 / Energy predictors + FrameProsodyRefiner (no flat pitch staircase!)
"""
def __init__(
self,
text_dim: int = 320,
n_mels: int = 100,
num_speakers: int = 4,
num_emotions: int = 8,
kernel_size: int = 5,
num_layers: int = 3,
):
super().__init__()
self.speaker_emb = nn.Embedding(num_speakers, text_dim)
self.emotion_emb = nn.Embedding(num_emotions, text_dim)
self.prior_conv = ConvNeXt1DBlock(text_dim, kernel_size=5, mult=2)
self.prior_linear = nn.Linear(text_dim, n_mels)
self.dur_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)
self.f0_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)
self.energy_predictor = ScalarPredictor(text_dim, kernel_size=kernel_size, num_layers=num_layers)
self.prosody_proj = nn.Linear(2, text_dim)
self.frame_prosody_net = FrameProsodyRefiner(text_dim, kernel_size=kernel_size)
def compute_prior(self, text_with_style: torch.Tensor, text_mask: torch.Tensor) -> torch.Tensor:
h = self.prior_conv(text_with_style, mask=text_mask)
return self.prior_linear(h) * text_mask.unsqueeze(-1).to(h.dtype)
def forward_train(
self,
text_feats: torch.Tensor,
text_mask: torch.Tensor,
speaker_ids: torch.Tensor,
emotion_ids: torch.Tensor,
mel_target: torch.Tensor,
mel_mask: torch.Tensor,
f0_target: torch.Tensor,
energy_target: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, torch.Tensor]]:
style = self.speaker_emb(speaker_ids) + self.emotion_emb(emotion_ids) # [B, D]
text_with_style = text_feats + style.unsqueeze(1)
prior_text = self.compute_prior(text_with_style, text_mask) # [B, T_x, M]
with torch.no_grad(), torch.autocast(device_type=mel_target.device.type, enabled=False):
p_fp32 = prior_text.float()
m_fp32 = mel_target.transpose(1, 2).float()
diff2 = (
p_fp32.pow(2).sum(dim=-1, keepdim=True)
+ m_fp32.pow(2).sum(dim=-1).unsqueeze(1)
- 2.0 * torch.bmm(p_fp32, m_fp32.transpose(1, 2))
)
attn = _maximum_path_lengths(-diff2, text_mask.sum(1), mel_mask.sum(1))
prior_mel = torch.bmm(attn.transpose(1, 2), prior_text).transpose(1, 2) # [B, M, T_y]
mel_mask_3d = mel_mask.unsqueeze(1).float()
prior_loss = F.l1_loss(prior_mel * mel_mask_3d, mel_target * mel_mask_3d, reduction="sum") / (
mel_mask_3d.sum() * mel_target.shape[1] + 1e-6
)
gt_dur = attn.sum(dim=2)
gt_log_dur = torch.log(gt_dur.clamp(min=1.0))
dur_safe = gt_dur.clamp(min=1.0)
# Average F0 over voiced frames only so unvoiced frames inside a token do not drag pitch down
vuv = (f0_target > 0.05).float()
vuv_tok = torch.bmm(attn, vuv.unsqueeze(-1)).squeeze(-1).clamp(min=1.0)
gt_f0_tok = torch.bmm(attn, (f0_target * vuv).unsqueeze(-1)).squeeze(-1) / vuv_tok
gt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safe
pred_log_dur = self.dur_predictor(text_feats, style, mask=text_mask)
pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)
pred_energy = self.energy_predictor(text_feats, style, mask=text_mask)
t_mask_f = text_mask.float()
t_denom = t_mask_f.sum().clamp(min=1.0)
dur_loss = F.mse_loss(pred_log_dur * t_mask_f, gt_log_dur * t_mask_f, reduction="sum") / t_denom
f0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / t_denom
energy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / t_denom
# Expand detached coarse prosody predictions and refine smoothly at frame resolution
prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1).detach() # [B, T_x, 2]
expanded_h = torch.bmm(attn.transpose(1, 2), text_with_style)
coarse_frame_prosody = torch.bmm(attn.transpose(1, 2), prosody_tok)
refined_frame_prosody = self.frame_prosody_net(
expanded_h, coarse_frame_prosody, self.prosody_proj, mask=mel_mask
)
target_frame_prosody = torch.stack([f0_target, energy_target], dim=-1)
m_mask_2d = mel_mask.unsqueeze(-1).float()
frame_prosody_loss = F.l1_loss(
refined_frame_prosody * m_mask_2d, target_frame_prosody * m_mask_2d, reduction="sum"
) / (m_mask_2d.sum() * 2.0 + 1e-6)
cond = (expanded_h + self.prosody_proj(refined_frame_prosody)) * mel_mask.unsqueeze(-1).to(expanded_h.dtype)
return cond.transpose(1, 2), prior_mel, {
"prior_loss": prior_loss,
"dur_loss": dur_loss,
"f0_loss": f0_loss,
"energy_loss": energy_loss,
"frame_prosody_loss": frame_prosody_loss,
}
def forward_infer(
self,
text_feats: torch.Tensor,
text_mask: torch.Tensor,
speaker_ids: torch.Tensor,
emotion_ids: torch.Tensor,
speed: float = 0.92,
min_frames: int = 2,
return_mask: bool = False,
):
style = self.speaker_emb(speaker_ids) + self.emotion_emb(emotion_ids)
text_with_style = text_feats + style.unsqueeze(1)
prior_text = self.compute_prior(text_with_style, text_mask)
log_dur = self.dur_predictor(text_feats, style, mask=text_mask).clamp(max=10.0)
durs = torch.clamp(torch.round(torch.exp(log_dur) / max(speed, 1e-3)), min=min_frames, max=250).long()
durs = durs * text_mask.long()
pred_f0 = self.f0_predictor(text_feats, style, mask=text_mask)
pred_energy = self.energy_predictor(text_feats, style, mask=text_mask)
prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)
expanded_h = expand_by_durations(text_with_style, durs)
coarse_frame_prosody = expand_by_durations(prosody_tok, durs)
mel_lengths = durs.sum(dim=1)
t_mel = expanded_h.shape[1]
mel_mask = torch.arange(t_mel, device=expanded_h.device).unsqueeze(0) < mel_lengths.unsqueeze(1)
refined_frame_prosody = self.frame_prosody_net(
expanded_h, coarse_frame_prosody, self.prosody_proj, mask=mel_mask
)
m_f = mel_mask.unsqueeze(-1).to(expanded_h.dtype)
cond_expanded = (expanded_h + self.prosody_proj(refined_frame_prosody)) * m_f
prior_expanded = expand_by_durations(prior_text, durs, max_len=t_mel) * m_f
if return_mask:
return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2), mel_mask
return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)