File size: 5,196 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""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)

    @torch.inference_mode()
    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