ECodec-FAST / ecodec_fast /nsf_source.py
Den4ikAI's picture
ECodec-FAST: codec extracted from ESpeech-V9-ECodec-FAST v2
0981df7 verified
Raw History Blame Contribute Delete
9.1 kB
"""NSF harmonic source — lifted from CosyVoice3 HiFTNet (cosyvoice/hifigan/generator.py),
self-contained. F0 -> sine harmonics -> merged excitation. Plus a light causal F0 predictor
(z86 -> F0 @86Hz) so we can supervise it with GT pitch during training.
Robovoice = iSTFT inventing phase from nothing. This gives the iSTFT head a real
harmonic-phase reference (excitation STFT), the way HiFTNet does.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.uniform import Uniform
class SineGen(nn.Module):
"""CosyVoice/HiFTNet SineGen (type 1). f0 [B,L,1] @audio-rate -> sines [B,L,harmonic+1]."""
def __init__(self, samp_rate, harmonic_num=0, sine_amp=0.1, noise_std=0.003, voiced_threshold=0):
super().__init__()
self.sine_amp, self.noise_std = sine_amp, noise_std
self.harmonic_num, self.sampling_rate, self.voiced_threshold = harmonic_num, samp_rate, voiced_threshold
def _f02uv(self, f0):
return (f0 > self.voiced_threshold).float()
@torch.no_grad()
def forward(self, f0): # f0 [B, L, 1]
f0 = f0.transpose(1, 2) # [B, 1, L]
F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1)), device=f0.device)
for i in range(self.harmonic_num + 1):
F_mat[:, i:i + 1, :] = f0 * (i + 1) / self.sampling_rate
theta = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
phase = Uniform(-np.pi, np.pi).sample((f0.size(0), self.harmonic_num + 1, 1)).to(f0.device)
phase[:, 0, :] = 0
sine = self.sine_amp * torch.sin(theta + phase)
uv = self._f02uv(f0)
noise = (uv * self.noise_std + (1 - uv) * self.sine_amp / 3) * torch.randn_like(sine)
sine = sine * uv + noise
return sine.transpose(1, 2), uv.transpose(1, 2), noise # [B,L,harm+1], [B,L,1], _
class SourceModuleHnNSF(nn.Module):
"""CosyVoice/HiFTNet source module. f0 [B,L,1] -> merged excitation [B,L,1]."""
def __init__(self, sampling_rate, harmonic_num=8, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0):
super().__init__()
self.sine_amp, self.noise_std = sine_amp, add_noise_std
self.l_sin_gen = SineGen(sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod)
self.l_linear = nn.Linear(harmonic_num + 1, 1)
self.l_tanh = nn.Tanh()
def forward(self, f0): # f0 [B, L, 1] @audio-rate
with torch.no_grad():
sine_wavs, uv, _ = self.l_sin_gen(f0)
sine_merge = self.l_tanh(self.l_linear(sine_wavs)) # [B, L, 1]
noise = torch.randn_like(uv) * self.sine_amp / 3
return sine_merge, noise, uv
class F0Predictor(nn.Module):
"""Light causal F0 predictor: z86 [B, C, T] @86Hz -> F0 [B, T] (Hz, >=0).
Trained with GT-pitch supervision (pyworld/torchaudio) — the part that made past NSF fail."""
def __init__(self, in_ch=1024, hid=256, k=5, n_layers=4):
super().__init__()
self.k = k
chs = [in_ch] + [hid] * n_layers
self.convs = nn.ModuleList([nn.Conv1d(chs[i], chs[i + 1], k) for i in range(n_layers)])
self.out = nn.Conv1d(hid, 1, 1)
def forward(self, z): # z [B, C, T] -> [B, T]
x = z
for c in self.convs:
x = F.elu(c(F.pad(x, (self.k - 1, 0)))) # causal (left pad)
return F.softplus(self.out(x)).squeeze(1) # [B, T] >= 0 Hz
class F0BinnedPredictor(nn.Module):
"""CREPE-style BINNED F0 classifier (fixes MSE-averaging -> octave mush).
z86 [B,C,T] -> per-bin activations [B, n_bins, T]; sigmoid+BCE with Gaussian soft
targets. Low total activation = unvoiced (UV gate free). Causal.
Optional reference conditioning (log-F0 mean/std of a speaker prompt) as FiLM = octave anchor (TTS)."""
def __init__(self, in_ch=1024, hid=256, k=5, n_layers=4, n_bins=256,
fmin=50.0, fmax=800.0, conf_thresh=0.5, ref_cond=False):
super().__init__()
self.k, self.n_bins, self.conf_thresh = k, n_bins, conf_thresh
chs = [in_ch] + [hid] * n_layers
self.convs = nn.ModuleList([nn.Conv1d(chs[i], chs[i + 1], k) for i in range(n_layers)])
self.out = nn.Conv1d(hid, n_bins, 1)
self.ref_cond = ref_cond
if ref_cond:
self.ref_film = nn.Linear(2, hid * 2) # [logf0_mean, logf0_std] -> gamma,beta
bin_hz = fmin * (fmax / fmin) ** torch.linspace(0, 1, n_bins)
self.register_buffer("bin_hz", bin_hz, persistent=False)
self.register_buffer("bin_log", torch.log(bin_hz), persistent=False)
def forward(self, z, ref=None): # z [B,C,T] -> logits [B, n_bins, T]
x = z
for i, c in enumerate(self.convs):
x = F.elu(c(F.pad(x, (self.k - 1, 0))))
if self.ref_cond and ref is not None and i == len(self.convs) - 1:
g, b = self.ref_film(ref).chunk(2, dim=-1) # ref [B,2] -> [B,hid]
x = x * (1 + g[..., None]) + b[..., None]
return self.out(x) # [B, n_bins, T]
def ref_logprior(self, ref_stats, width_mult=2.0):
"""Gaussian log-prior over bins from reference (log-F0 mean, std) -> [1, n_bins, 1].
Added to logits before decode: anchors the octave to the speaker's range.
Only possible because this is a classifier (a regressor has nowhere to put a prior)."""
mu, sd = ref_stats
bl = self.bin_log.view(1, -1, 1)
return -0.5 * ((bl - mu) / (width_mult * max(float(sd), 1e-2))) ** 2
@torch.no_grad()
def decode(self, logits, window=4, ref_stats=None, prior_strength=0.0, width_mult=2.0):
"""logits [B,n_bins,T] -> F0 [B,T] (0=unvoiced). With ref_stats+prior_strength>0 the
prediction is pulled toward the reference F0 range (kills octave derailment)."""
if ref_stats is not None and prior_strength > 0:
logits = logits + prior_strength * self.ref_logprior(ref_stats, width_mult)
act = torch.sigmoid(logits) # [B, nb, T]
B, nb, T = act.shape
conf, arg = act.max(1) # [B, T]
ii = torch.arange(nb, device=logits.device).view(1, nb, 1)
mask = ((ii >= (arg - window).unsqueeze(1)) & (ii <= (arg + window).unsqueeze(1))).float()
w = act * mask
f0log = (w * self.bin_log.view(1, nb, 1)).sum(1) / w.sum(1).clamp(min=1e-6)
f0 = torch.exp(f0log)
return torch.where(conf > self.conf_thresh, f0, torch.zeros_like(f0)) # UV gate
@staticmethod
@torch.no_grad()
def ref_stats_from_wav(wav, sr, device="cpu", conf=0.5):
"""Reference speaker prompt -> (log-F0 mean, log-F0 std) for ref_logprior.
Uses torchcrepe (imported lazily). Returns None if the clip has too little voiced speech."""
import torchaudio
import torchcrepe
from torchcrepe.model import Crepe
import os as _os
if wav.dim() == 1:
wav = wav[None]
wav = wav.mean(0, keepdim=True)
w16 = torchaudio.functional.resample(wav, sr, 16000).to(device) if sr != 16000 else wav.to(device)
cache = getattr(F0BinnedPredictor, "_crepe_cache", {})
if device not in cache:
m = Crepe("tiny")
m.load_state_dict(torch.load(_os.path.join(_os.path.dirname(torchcrepe.__file__), "assets", "tiny.pth"),
map_location="cpu"))
cache[device] = m.to(device).eval()
F0BinnedPredictor._crepe_cache = cache
cm = cache[device]
hop = 186 # 16k frames matching ~86Hz z86 rate
x = F.pad(w16, (512, 512))
n = 1 + (x.shape[1] - 1024) // hop
idx = torch.arange(1024, device=device)[None, :] + hop * torch.arange(n, device=device)[:, None]
fr = x[:, idx].reshape(n, 1024)
fr = fr - fr.mean(1, keepdim=True); fr = fr / (fr.std(1, keepdim=True) + 1e-8)
act = cm(fr); pd, arg = act.max(-1)
ii = torch.arange(360, device=device)[None, :]
m = ((ii >= (arg - 4)[:, None]) & (ii <= (arg + 4)[:, None])).float()
w = act * m
binc = (w * ii).sum(-1) / w.sum(-1).clamp(min=1e-6)
f0 = 10 * 2 ** ((1997.3794084376191 + 20 * binc) / 1200)
v = pd > conf
if v.sum() < 5:
return None
lg = torch.log(f0[v].clamp(min=1.0))
return float(lg.mean()), float(lg.std().clamp(min=0.1))
def soft_targets(self, f0_gt, voiced, sigma_bins=1.5): # f0_gt [B,T] Hz, voiced [B,T] -> [B, nb, T]
lg = torch.log(f0_gt.clamp(min=1.0))
d = lg.unsqueeze(1) - self.bin_log.view(1, -1, 1) # [B, nb, T]
bw = (self.bin_log[1] - self.bin_log[0])
t = torch.exp(-0.5 * (d / (sigma_bins * bw)) ** 2)
return t * voiced.unsqueeze(1).float() # zeros where unvoiced