Murli-V1.5-Code / models /prosody_aligner.py
ViuAI's picture
Audit fixes: optimizer-step checkpoints, train/infer prosody parity, spoken numbers, narrate.py, 6/6 tests pass
cc5e704 verified
Raw History Blame Contribute Delete
10.8 kB
"""
Murli V1.5 Alignment, Duration, Log-F0 Pitch, Energy & ConvNeXt Mel Prior Module.
Fixes V1's flat monotone prosody (5.0/10) and weak nn.Linear prior (Prior Loss ~1.04).
Strictly computes MAS in FP32 with Numba parallel JIT + NumPy fallback.
"""
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), -1e9, 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."""
bsz, _, _ = value.shape
mask_bool = mask.bool()
val_np = value.detach().float().cpu().numpy()
mask_np = mask_bool.cpu().numpy()
path = np.zeros_like(val_np, dtype=np.float32)
t_xs = np.empty(bsz, dtype=np.int64)
t_ys = np.empty(bsz, dtype=np.int64)
for b in range(bsz):
tx = int(mask_np[b, :, 0].sum()) if mask_np[b].any() else 0
ty = int(mask_np[b, 0, :].sum()) if mask_np[b].any() else 0
if tx <= 0 or ty <= 0 or tx > ty:
raise ValueError(f"Sequence (T_text={tx}, T_mel={ty}) cannot be aligned monotonically.")
t_xs[b] = tx
t_ys[b] = ty
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 ProsodyAndAlignmentModule(nn.Module):
"""
Single-speaker expressive Prosody + Alignment module:
- Emotion embedding (neutral=0, happy, sad, angry, story, etc.)
- ConvNeXt Mel Prior (replaces V1's weak nn.Linear)
- Duration + Log-F0 + Energy predictors
- Prosody projection back into expanded acoustic conditioning
"""
def __init__(
self,
text_dim: int = 320,
n_mels: int = 100,
num_emotions: int = 8,
kernel_size: int = 5,
num_layers: int = 3,
):
super().__init__()
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)
# Injects [log_f0, energy] back into expanded acoustic features [B, T_mel, D]
self.prosody_proj = nn.Linear(2, text_dim)
def compute_prior(self, text_feats: torch.Tensor, text_mask: torch.Tensor) -> torch.Tensor:
h = self.prior_conv(text_feats, 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,
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]]:
"""
Aligns text_feats [B, T_x, D] with mel_target [B, M, T_y] via FP32 MAS.
Returns:
cond_mel: [B, D, T_y] expanded conditioning with F0+Energy+Emotion
prior_mel: [B, M, T_y] expanded prior mel
losses: dict with prior_loss, dur_loss, f0_loss, energy_loss
"""
emo = self.emotion_emb(emotion_ids) # [B, D]
text_with_emo = text_feats + emo.unsqueeze(1)
prior_text = self.compute_prior(text_with_emo, text_mask) # [B, T_x, M]
# FP32 negative L2 distance score matrix [B, T_x, T_y]
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() # [B, T_y, M]
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_mask = text_mask.unsqueeze(2) & mel_mask.unsqueeze(1)
attn = maximum_path(-diff2, attn_mask) # [B, T_x, T_y]
# Prior loss against aligned target
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
)
# Token-level durations from MAS path
gt_dur = attn.sum(dim=2) # [B, T_x]
gt_log_dur = torch.log(gt_dur.clamp(min=1.0))
# Average frame-level F0 and Energy per aligned token
dur_safe = gt_dur.clamp(min=1.0)
gt_f0_tok = torch.bmm(attn, f0_target.unsqueeze(-1)).squeeze(-1) / dur_safe
gt_energy_tok = torch.bmm(attn, energy_target.unsqueeze(-1)).squeeze(-1) / dur_safe
# Predictors (detach text_with_emo slightly or keep full grad for joint prosody)
pred_log_dur = self.dur_predictor(text_feats, emo, mask=text_mask)
pred_f0 = self.f0_predictor(text_feats, emo, mask=text_mask)
pred_energy = self.energy_predictor(text_feats, emo, mask=text_mask)
t_mask_f = text_mask.float()
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") / denom
f0_loss = F.l1_loss(pred_f0 * t_mask_f, gt_f0_tok * t_mask_f, reduction="sum") / denom
energy_loss = F.l1_loss(pred_energy * t_mask_f, gt_energy_tok * t_mask_f, reduction="sum") / denom
# The acoustic decoder sees the same predicted prosody at training and inference.
prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1)
token_cond = text_with_emo + self.prosody_proj(prosody_tok)
cond = torch.bmm(attn.transpose(1, 2), token_cond)
return cond.transpose(1, 2), prior_mel, {
"prior_loss": prior_loss,
"dur_loss": dur_loss,
"f0_loss": f0_loss,
"energy_loss": energy_loss,
}
def forward_infer(
self,
text_feats: torch.Tensor,
text_mask: torch.Tensor,
emotion_ids: torch.Tensor,
speed: float = 0.92,
min_frames: int = 2,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Inference expansion (PyTorch eager)."""
emo = self.emotion_emb(emotion_ids)
text_with_emo = text_feats + emo.unsqueeze(1)
prior_text = self.compute_prior(text_with_emo, text_mask)
log_dur = self.dur_predictor(text_feats, emo, mask=text_mask)
durs = torch.clamp(torch.round(torch.exp(log_dur) / max(speed, 1e-3)), min=min_frames).long()
durs = durs * text_mask.long()
pred_f0 = self.f0_predictor(text_feats, emo, mask=text_mask)
pred_energy = self.energy_predictor(text_feats, emo, mask=text_mask)
prosody_tok = torch.stack([pred_f0, pred_energy], dim=-1) # [B, T_x, 2]
token_cond = text_with_emo + self.prosody_proj(prosody_tok)
cond_expanded = expand_by_durations(token_cond, durs)
prior_expanded = expand_by_durations(prior_text, durs)
return cond_expanded.transpose(1, 2), prior_expanded.transpose(1, 2)