ECodec-FAST / ecodec_fast /model_nsf_v2.py
Den4ikAI's picture
ECodec-FAST: codec extracted from ESpeech-V9-ECodec-FAST v2
0981df7 verified
Raw History Blame Contribute Delete
4.1 kB
"""NSFNanoDecoder V2: NSF source driven by a CREPE-style BINNED F0 classifier
(F0BinnedPredictor) instead of MSE-regression -> no octave-averaging mush, free UV gate.
Backbone (proj/blocks/norm/head/source_proj/m_source) IDENTICAL to NSFNanoDecoder ->
warm-start from a v1 nsf checkpoint (the binned f0-head reinits; f0 conv-trunk transfers)."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from nano_core import CausalConvNeXt, Z86_DIM
from istft_head import ISTFTHead
from nsf_source import SourceModuleHnNSF, F0BinnedPredictor
class NSFNanoDecoderV2(nn.Module):
def __init__(self, in_dim: int = Z86_DIM, dim: int = 768, n_blocks: int = 12,
n_fft: int = 1116, hop: int = 279, sr: int = 24000, harmonic_num: int = 8,
n_bins: int = 256, fmin: float = 50.0, fmax: float = 800.0, ref_cond: bool = False):
super().__init__()
self.proj = nn.Conv1d(in_dim, dim, 1)
self.blocks = nn.ModuleList([CausalConvNeXt(dim) for _ in range(n_blocks)])
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.head = ISTFTHead(dim=dim, n_fft=n_fft, hop_length=hop, padding="same")
self.f0_predictor = F0BinnedPredictor(in_ch=in_dim, hid=256, n_bins=n_bins,
fmin=fmin, fmax=fmax, ref_cond=ref_cond)
self.m_source = SourceModuleHnNSF(sr, harmonic_num=harmonic_num)
self.source_proj = nn.Conv1d(n_fft + 2, dim, 1)
self.hop, self.n_fft, self.sr = hop, n_fft, sr
self.register_buffer("src_win", torch.hann_window(n_fft), persistent=False)
def _excitation_spec(self, z86, ref=None, ref_stats=None, prior_strength=0.0):
logits = self.f0_predictor(z86, ref) # [B, n_bins, T]
f0 = self.f0_predictor.decode(logits, ref_stats=ref_stats,
prior_strength=prior_strength) # [B, T] Hz (0=unvoiced)
f0_up = F.interpolate(f0[:, None], scale_factor=self.hop, mode="nearest")[:, 0]
src, _, _ = self.m_source(f0_up[..., None])
with torch.autocast(z86.device.type, enabled=False):
s = torch.stft(src.squeeze(-1).float(), self.n_fft, self.hop, self.n_fft,
self.src_win.float(), center=True, return_complex=True)
return torch.cat([s.real, s.imag], dim=1), logits, f0
def forward(self, z86, return_f0: bool = False, ref=None,
ref_stats=None, prior_strength: float = 0.0):
"""ref_stats=(log-F0 mean, std) of a speaker prompt + prior_strength>0 anchors the
predicted pitch to that speaker's range (see F0BinnedPredictor.ref_stats_from_wav)."""
x = self.proj(z86)
s_feat, logits, f0 = self._excitation_spec(z86, ref, ref_stats, prior_strength)
Tm = min(s_feat.shape[-1], x.shape[-1])
x = x[..., :Tm] + self.source_proj(s_feat[..., :Tm])
for b in self.blocks:
x = b(x)
x = self.norm(x.transpose(1, 2))
audio = self.head(x)
return (audio, logits[..., :Tm], f0[..., :Tm]) if return_f0 else audio
def load_backbone(self, state):
"""Warm-start matching-shape tensors from a v1 NSFNanoDecoder (or v2) state_dict.
f0_predictor conv-trunk transfers (same shape); the binned head (out) reinits."""
own = self.state_dict()
loaded = {k: v for k, v in state.items() if k in own and own[k].shape == v.shape}
own.update(loaded)
self.load_state_dict(own)
return len(loaded), len(state)
if __name__ == "__main__":
torch.set_grad_enabled(False)
g = NSFNanoDecoderV2(dim=768, n_blocks=12).eval()
n = sum(p.numel() for p in g.parameters())
z = torch.randn(2, 1024, 40)
a, logits, f0 = g(z, return_f0=True)
print(f"NSFNanoDecoderV2 {n/1e6:.2f}M | z {tuple(z.shape)} -> audio {tuple(a.shape)} "
f"logits {tuple(logits.shape)} f0 {tuple(f0.shape)}")
print(f"audio finite: {torch.isfinite(a).all().item()} | f0 range [{f0.min():.0f},{f0.max():.0f}]Hz "
f"| unvoiced frames: {(f0[0]==0).sum().item()}/{f0.shape[-1]}")