Download code/src/lua_nova_v1/models/bigvgan.py from oProfM/LuaNovaV1: direct link, hf CLI and curl.
- Browser
- Download file 5.2 kB
-
https://huggingface.co/oProfM/LuaNovaV1/resolve/main/code/src/lua_nova_v1/models/bigvgan.py
- Command line
-
hf download hf://oProfM/LuaNovaV1/code/src/lua_nova_v1/models/bigvgan.py
-
curl -L -o bigvgan.py https://huggingface.co/oProfM/LuaNovaV1/resolve/main/code/src/lua_nova_v1/models/bigvgan.py
5.2 kB
| """MIT-licensed BigVGAN-v2 / BigVGAN-base 24 kHz 100-band Slaney mel extractor and vocoder wrapper.""" | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import sys | |
| from librosa.filters import mel as librosa_mel_fn | |
| import torch | |
| from torch import nn | |
| import torch.nn.functional as F | |
| _REPO_ROOT = Path(__file__).resolve().parents[3] | |
| _BIGVGAN_DIR = _REPO_ROOT / "third_party" / "bigvgan" | |
| def _ensure_bigvgan_importable() -> None: | |
| if str(_BIGVGAN_DIR) not in sys.path: | |
| sys.path.insert(0, str(_BIGVGAN_DIR)) | |
| try: | |
| import truststore | |
| truststore.inject_into_ssl() | |
| except ImportError: | |
| pass | |
| class BigVGANMelExtractor(nn.Module): | |
| """Exact 24 kHz 100-band Slaney log-mel extractor matching MIT BigVGAN ``meldataset.py``.""" | |
| def __init__( | |
| self, | |
| sample_rate: int = 24000, | |
| n_fft: int = 1024, | |
| hop_size: int = 256, | |
| win_size: int = 1024, | |
| n_mels: int = 100, | |
| fmin: float = 0.0, | |
| fmax: float | None = None, | |
| ) -> None: | |
| super().__init__() | |
| self.sample_rate = int(sample_rate) | |
| self.n_fft = int(n_fft) | |
| self.hop_size = int(hop_size) | |
| self.win_size = int(win_size) | |
| self.n_mels = int(n_mels) | |
| self.fmin = float(fmin) | |
| self.fmax = fmax | |
| mel_np = librosa_mel_fn( | |
| sr=self.sample_rate, | |
| n_fft=self.n_fft, | |
| n_mels=self.n_mels, | |
| fmin=self.fmin, | |
| fmax=self.fmax, | |
| ) | |
| self.register_buffer("mel_basis", torch.from_numpy(mel_np).float(), persistent=False) | |
| self.register_buffer("hann_window", torch.hann_window(self.win_size).float(), persistent=False) | |
| def forward(self, wave: torch.Tensor) -> torch.Tensor: | |
| """Compute BigVGAN Slaney log-mel ``[B, T, 100]`` from 24 kHz waveform ``[B, T*256]`` (or ``[T*256]``).""" | |
| w = wave.float() | |
| if w.dim() == 1: | |
| w = w.unsqueeze(0) | |
| pad = (self.n_fft - self.hop_size) // 2 | |
| if w.shape[-1] <= pad: | |
| w = F.pad(w.unsqueeze(1), (pad, pad), mode="constant").squeeze(1) | |
| else: | |
| w = F.pad(w.unsqueeze(1), (pad, pad), mode="reflect").squeeze(1) | |
| spec = torch.stft( | |
| w, | |
| self.n_fft, | |
| hop_length=self.hop_size, | |
| win_length=self.win_size, | |
| window=self.hann_window, | |
| center=False, | |
| pad_mode="reflect", | |
| normalized=False, | |
| onesided=True, | |
| return_complex=True, | |
| ) | |
| mag = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9) | |
| mel = torch.matmul(self.mel_basis, mag) | |
| log_mel = torch.log(torch.clamp(mel, min=1e-5)) | |
| return log_mel.transpose(1, 2).contiguous() | |
| class BigVGANVocoderWrapper(nn.Module): | |
| """Thin inference wrapper over MIT NVIDIA BigVGAN-v2 / BigVGAN-base 24 kHz 100-band.""" | |
| def __init__( | |
| self, | |
| model_id: str = "nvidia/bigvgan_v2_24khz_100band_256x", | |
| ckpt_path: Path | None = None, | |
| device: str = "cuda", | |
| use_cuda_kernel: bool = False, | |
| ) -> None: | |
| super().__init__() | |
| _ensure_bigvgan_importable() | |
| import bigvgan | |
| from env import AttrDict | |
| if ckpt_path is not None: | |
| ck = torch.load(ckpt_path, map_location="cpu", weights_only=True) | |
| self.model_id = str(ck.get("model_id", model_id)) | |
| if "h" in ck: | |
| model = bigvgan.BigVGAN(AttrDict(ck["h"]), use_cuda_kernel=use_cuda_kernel) | |
| else: | |
| model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel) | |
| if ck.get("weight_norm_removed", False): | |
| model.remove_weight_norm() | |
| model.load_state_dict(ck["state_dict"], strict=True) | |
| else: | |
| model.load_state_dict(ck["state_dict"], strict=True) | |
| model.remove_weight_norm() | |
| else: | |
| self.model_id = str(model_id) | |
| model = bigvgan.BigVGAN.from_pretrained(self.model_id, use_cuda_kernel=use_cuda_kernel) | |
| model.remove_weight_norm() | |
| self.net = model.eval().to(device) | |
| for p in self.net.parameters(): | |
| p.requires_grad_(False) | |
| self.hop_size = int(self.net.h.hop_size) | |
| self.sample_rate = int(self.net.h.sampling_rate) | |
| def decode_raw_mel(self, phys_mel: torch.Tensor, lengths: torch.Tensor | None = None) -> torch.Tensor: | |
| """Synthesize 24 kHz waveform ``[B, T*hop]`` from physical log-mel ``[B, T, 100]``.""" | |
| mel_bct = phys_mel.float().transpose(1, 2).contiguous() | |
| wav = self.net(mel_bct).squeeze(1) | |
| if lengths is not None: | |
| total = phys_mel.shape[1] * self.hop_size | |
| if wav.shape[1] > total: | |
| wav = wav[:, :total] | |
| sample_mask = (torch.arange(wav.shape[1], device=wav.device)[None] < (lengths.to(wav.device)[:, None] * self.hop_size)).float() | |
| wav = wav * sample_mask | |
| return wav | |