File size: 4,417 Bytes
a1cd84e | 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 | """
Murli V2.0 Zero-Shot Speaker & Style Perceiver Encoder.
Extracts fixed-length latent timbre/prosody tokens [B, N_style, D] and global speaker
conditioning [B, D] from any 3-10s reference mel spectrogram (Hindi or English).
"""
from typing import Optional, Tuple
import torch
import torch.nn as nn
from models.layers import MultiHeadSDPA, RMSNorm, SwiGLU
class PerceiverBlock(nn.Module):
def __init__(self, dim: int, num_heads: int, dropout: float = 0.05):
super().__init__()
self.norm_q = RMSNorm(dim)
self.norm_kv = RMSNorm(dim)
self.cross_attn = MultiHeadSDPA(dim, num_heads, kv_dim=dim, dropout=dropout, use_rope=False)
self.norm_self = RMSNorm(dim)
self.self_attn = MultiHeadSDPA(dim, num_heads, dropout=dropout, use_rope=False)
self.norm_mlp = RMSNorm(dim)
self.mlp = SwiGLU(dim, ff_mult=2.667, dropout=dropout)
def forward(
self,
latents: torch.Tensor,
ref_feats: torch.Tensor,
ref_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
latents = latents + self.cross_attn(
self.norm_q(latents), kv=self.norm_kv(ref_feats), key_padding_mask=ref_mask
)
latents = latents + self.self_attn(self.norm_self(latents))
latents = latents + self.mlp(self.norm_mlp(latents))
return latents
class ZeroShotStyleEncoder(nn.Module):
"""Perceiver Resampler converting variable-length reference mel [B, M, T_ref] into style tokens + global spk emb."""
def __init__(
self,
n_mels: int = 100,
dim: int = 384,
num_latents: int = 16,
num_layers: int = 4,
num_heads: int = 6,
dropout: float = 0.05,
):
super().__init__()
self.dim = dim
self.num_latents = num_latents
# Frame-level acoustic encoder with 4x temporal downsampling
self.mel_in = nn.Sequential(
nn.Conv1d(n_mels, dim, kernel_size=5, padding=2),
nn.GELU(),
nn.Conv1d(dim, dim, kernel_size=5, stride=2, padding=2),
nn.GELU(),
nn.Conv1d(dim, dim, kernel_size=3, stride=2, padding=1),
nn.GELU(),
)
self.latents = nn.Parameter(torch.randn(1, num_latents, dim) * 0.02)
self.null_style_tokens = nn.Parameter(torch.zeros(1, num_latents, dim))
self.null_global_emb = nn.Parameter(torch.zeros(1, dim))
self.blocks = nn.ModuleList([
PerceiverBlock(dim, num_heads, dropout=dropout) for _ in range(num_layers)
])
self.out_norm = RMSNorm(dim)
self.global_proj = nn.Sequential(
nn.Linear(dim, dim),
nn.SiLU(),
nn.Linear(dim, dim),
)
def forward(
self,
ref_mel: Optional[torch.Tensor] = None,
ref_mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
ref_mel: [B, n_mels, T_ref] or None (returns unconditional null embeddings).
ref_mask: [B, T_ref] bool mask or None.
Returns:
style_tokens: [B, num_latents, dim]
global_emb: [B, dim]
"""
if ref_mel is None:
raise ValueError("Call null_style(batch_size, device) when ref_mel is omitted.")
bsz = ref_mel.shape[0]
h = ref_mel
down_mask = ref_mask
for layer in self.mel_in:
if isinstance(layer, nn.Conv1d) and down_mask is not None:
h = h.masked_fill(~down_mask[:, None], 0)
down_mask = down_mask[:, ::layer.stride[0]]
h = layer(h)
feats = h.transpose(1, 2)
latents = self.latents.expand(bsz, -1, -1)
for blk in self.blocks:
latents = blk(latents, feats, ref_mask=down_mask)
style_tokens = self.out_norm(latents)
global_emb = self.global_proj(style_tokens.mean(dim=1))
return style_tokens, global_emb
def null_style(self, batch_size: int, device: torch.device, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]:
return (
self.null_style_tokens.expand(batch_size, -1, -1).to(device=device, dtype=dtype),
self.null_global_emb.expand(batch_size, -1).to(device=device, dtype=dtype),
)
|