Binned-F0 decoder only: drop v1 decoder, encoder-only checkpoint
Browse files- README.md +22 -25
- ecodec_fast.pth → ecodec_encoder.pth +2 -2
- ecodec_fast/__init__.py +1 -1
- ecodec_fast/codec_fast.py +52 -199
README.md
CHANGED
|
@@ -14,13 +14,14 @@ tags:
|
|
| 14 |
# ECodec-FAST
|
| 15 |
|
| 16 |
Нейросетевой аудиокодек из [ESpeech-V9-ECodec-FAST](https://huggingface.co/ESpeech/ESpeech-V9-ECodec-FAST), вынесенный
|
| 17 |
-
отдельно от TTS: родной энкодер и квантайзер ECodec плюс
|
|
|
|
| 18 |
|
| 19 |
```
|
| 20 |
аудио 44.1 кГц ─► энкодер ECodec ─► RVQ: 10 кодбуков @ 21.53 Гц
|
| 21 |
(cb0 семантический, 4096; cb1..cb9 — 1024)
|
| 22 |
-
коды ─►
|
| 23 |
-
|
| 24 |
```
|
| 25 |
|
| 26 |
| | |
|
|
@@ -28,17 +29,17 @@ tags:
|
|
| 28 |
| вход | 44.1 кГц, моно (другие частоты ресемплируются) |
|
| 29 |
| выход | 24 кГц, моно |
|
| 30 |
| коды | `LongTensor [10, T]`, 21.53 кадра/с |
|
| 31 |
-
| декодирование | каузальное, стримится чанками |
|
| 32 |
|
| 33 |
## Файлы
|
| 34 |
|
| 35 |
| файл | размер | что |
|
| 36 |
|---|---|---|
|
| 37 |
-
| `
|
| 38 |
-
| `nano_nsf_v2_60k.pt` | 181 МБ | декодер
|
| 39 |
-
| `postvq_student_90k.pt` | 56 МБ | дистиллированный post-VQ
|
| 40 |
-
| `ecodec_quantizer_slim.pt` | 81 МБ | кодбуки + upsample для фронтенда
|
| 41 |
-
| `ecodec_fast/` | — | код (
|
| 42 |
|
| 43 |
## Быстрый старт
|
| 44 |
|
|
@@ -49,34 +50,30 @@ cd ECodec-FAST && pip install -r requirements.txt
|
|
| 49 |
|
| 50 |
```python
|
| 51 |
import torchaudio
|
| 52 |
-
from ecodec_fast import ECodecFast
|
| 53 |
|
| 54 |
codec = ECodecFast() # веса из корня репо (или $ECODEC_WEIGHTS), device="cpu"
|
| 55 |
codes = codec.encode_file("in.wav") # LongTensor [10, T] @ 21.53 Гц
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
torchaudio.save("out_v1.wav", audio[None], 24000)
|
| 60 |
|
| 61 |
-
# д
|
| 62 |
-
|
| 63 |
-
audio =
|
| 64 |
-
audio = dec.from_codes(codes, ref=dec.speaker_ref("speaker.wav")) # режим B: питч привязан к голосу (нужен torchcrepe)
|
| 65 |
-
torchaudio.save("out_v2.wav", audio.cpu(), 24000)
|
| 66 |
```
|
| 67 |
|
| 68 |
-
|
| 69 |
-
Декодеру v2 нужно не меньше 3 кодбуков (`nq >= 3`); на 1–2 вокализация разваливается.
|
| 70 |
|
| 71 |
-
CLI: `python ecodec_fast/codec_fast.py --in_wav in.wav --out_wav out.wav [--nq 10] [--device cuda]`.
|
| 72 |
|
| 73 |
## Переменные окружения
|
| 74 |
|
| 75 |
* `ECODEC_WEIGHTS` — папка с весами, если они лежат не в корне репо.
|
| 76 |
-
* `ESP_POSTVQ=teacher` + `ESP_POSTVQ_TEACHER=<путь>` —
|
| 77 |
|
| 78 |
## Заметки
|
| 79 |
|
| 80 |
-
*
|
| 81 |
-
*
|
| 82 |
-
|
|
|
|
| 14 |
# ECodec-FAST
|
| 15 |
|
| 16 |
Нейросетевой аудиокодек из [ESpeech-V9-ECodec-FAST](https://huggingface.co/ESpeech/ESpeech-V9-ECodec-FAST), вынесенный
|
| 17 |
+
отдельно от TTS: родной энкодер и квантайзер ECodec плюс быстрый декодер nano-NSF v2 с **binned F0**
|
| 18 |
+
(питч предсказывается классификацией по бинам, поэтому тон не плывёт, в отличие от регрессионного F0 в декодере v1).
|
| 19 |
|
| 20 |
```
|
| 21 |
аудио 44.1 кГц ─► энкодер ECodec ─► RVQ: 10 кодбуков @ 21.53 Гц
|
| 22 |
(cb0 семантический, 4096; cb1..cb9 — 1024)
|
| 23 |
+
коды ─► фронтенд (from_codes + дистиллят post-VQ 14.7M + upsample) ─► z @ 86 Гц
|
| 24 |
+
─► NSF-декодер с binned F0 ─► 24 кГц
|
| 25 |
```
|
| 26 |
|
| 27 |
| | |
|
|
|
|
| 29 |
| вход | 44.1 кГц, моно (другие частоты ресемплируются) |
|
| 30 |
| выход | 24 кГц, моно |
|
| 31 |
| коды | `LongTensor [10, T]`, 21.53 кадра/с |
|
| 32 |
+
| декодирование | каузальное, стримится чанками; нужно `nq >= 3` кодбуков |
|
| 33 |
|
| 34 |
## Файлы
|
| 35 |
|
| 36 |
| файл | размер | что |
|
| 37 |
|---|---|---|
|
| 38 |
+
| `ecodec_encoder.pth` | 398 МБ | энкодер + квантайзер ECodec (fp16 на диске, считается в fp32) |
|
| 39 |
+
| `nano_nsf_v2_60k.pt` | 181 МБ | декодер NSF с binned F0 |
|
| 40 |
+
| `postvq_student_90k.pt` | 56 МБ | дистиллированный post-VQ |
|
| 41 |
+
| `ecodec_quantizer_slim.pt` | 81 МБ | кодбуки + upsample для фронтенда декодера |
|
| 42 |
+
| `ecodec_fast/` | — | код (нужны только torch, torchaudio, numpy) |
|
| 43 |
|
| 44 |
## Быстрый старт
|
| 45 |
|
|
|
|
| 50 |
|
| 51 |
```python
|
| 52 |
import torchaudio
|
| 53 |
+
from ecodec_fast import ECodecFast
|
| 54 |
|
| 55 |
codec = ECodecFast() # веса из корня репо (или $ECODEC_WEIGHTS), device="cpu"
|
| 56 |
codes = codec.encode_file("in.wav") # LongTensor [10, T] @ 21.53 Гц
|
| 57 |
|
| 58 |
+
audio = codec.decode(codes) # [L] @ 24 кГц, питч предсказывается по кодам
|
| 59 |
+
torchaudio.save("out.wav", audio[None], 24000)
|
|
|
|
| 60 |
|
| 61 |
+
# питч, привязанный к диапазону конкретного голоса (нужен torchcrepe)
|
| 62 |
+
ref = codec.speaker_ref("speaker.wav")
|
| 63 |
+
audio = codec.decode(codes, ref=ref)
|
|
|
|
|
|
|
| 64 |
```
|
| 65 |
|
| 66 |
+
Декодер можно взять и отдельно: `from ecodec_fast import NanoDecoderV2; NanoDecoderV2().from_codes(codes)`.
|
|
|
|
| 67 |
|
| 68 |
+
CLI: `python ecodec_fast/codec_fast.py --in_wav in.wav --out_wav out.wav [--nq 10] [--device cuda] [--speaker_ref spk.wav]`.
|
| 69 |
|
| 70 |
## Переменные окружения
|
| 71 |
|
| 72 |
* `ECODEC_WEIGHTS` — папка с весами, если они лежат не в корне репо.
|
| 73 |
+
* `ESP_POSTVQ=teacher` + `ESP_POSTVQ_TEACHER=<путь>` — исходный post-VQ (учитель, 109M; в этот репо не входит).
|
| 74 |
|
| 75 |
## Заметки
|
| 76 |
|
| 77 |
+
* Коды и звук совпадают с прод-сборкой ESpeech-V9-ECodec-FAST v2 бит-в-бит.
|
| 78 |
+
* В NSF-источнике есть шум, поэтому для воспроизводимого выхода фиксируйте `torch.manual_seed` после загрузки декодера.
|
| 79 |
+
* `ISTFTHead` взят из [vocos](https://github.com/gemelo-ai/vocos) (MIT) и вшит в `ecodec_fast/istft_head.py`.
|
ecodec_fast.pth → ecodec_encoder.pth
RENAMED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:817283aa45bbc732a7eb85c28822120ee037c93b5f14bf08798f39b5e3e0456f
|
| 3 |
+
size 417198749
|
ecodec_fast/__init__.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""ECodec-FAST: ECodec 44.1 kHz encoder + RVQ (10 codebooks @21.53 Hz)
|
| 2 |
|
| 3 |
from ecodec_fast import ECodecFast, NanoDecoderV2
|
| 4 |
"""
|
|
|
|
| 1 |
+
"""ECodec-FAST: ECodec 44.1 kHz encoder + RVQ (10 codebooks @21.53 Hz) + binned-F0 nano-NSF 24 kHz decoder.
|
| 2 |
|
| 3 |
from ecodec_fast import ECodecFast, NanoDecoderV2
|
| 4 |
"""
|
ecodec_fast/codec_fast.py
CHANGED
|
@@ -1,206 +1,61 @@
|
|
| 1 |
-
"""ECodec-
|
| 2 |
-
|
| 3 |
-
Native ECodec encoder + quantizer, with the heavy 54M conv decoder REPLACED by a
|
| 4 |
-
compact NSF-hybrid iSTFT decoder (41M) that runs ~20-36x realtime on CPU and is
|
| 5 |
-
free of the "robovoice" phase artefact.
|
| 6 |
|
| 7 |
codec: ECodec 44.1kHz, RVQ 10 codebooks @21.53Hz (cb0 semantic 4096 + 9 residual 1024)
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
Usage:
|
| 12 |
-
from ecodec_fast import ECodecFast
|
| 13 |
m = ECodecFast() # weights from the repo root, cpu by default
|
| 14 |
codes = m.encode_file("in.wav") # -> LongTensor [10, T]
|
| 15 |
-
m.decode_to_file(codes, "out.wav"
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
single ecodec_fast.pth (fp16 on disk, run in fp32).
|
| 20 |
"""
|
| 21 |
-
import os
|
|
|
|
|
|
|
| 22 |
import numpy as np
|
| 23 |
-
import torch
|
|
|
|
| 24 |
import torchaudio
|
| 25 |
-
from torch.distributions.uniform import Uniform
|
| 26 |
|
| 27 |
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # local ECodec class defs
|
| 28 |
-
from ecodec import ECodec
|
| 29 |
-
from istft_head import ISTFTHead
|
| 30 |
-
|
| 31 |
-
Z86_DIM = 1024
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# ============================ vendored decoder ============================
|
| 35 |
-
class CausalConvNeXt(nn.Module):
|
| 36 |
-
def __init__(self, dim, kernel=7, mult=3):
|
| 37 |
-
super().__init__()
|
| 38 |
-
self.pad = kernel - 1
|
| 39 |
-
self.dw = nn.Conv1d(dim, dim, kernel, groups=dim)
|
| 40 |
-
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
| 41 |
-
self.pw1 = nn.Linear(dim, dim * mult); self.act = nn.GELU(); self.pw2 = nn.Linear(dim * mult, dim)
|
| 42 |
-
self.gamma = nn.Parameter(1e-6 * torch.ones(dim))
|
| 43 |
-
|
| 44 |
-
def forward(self, x):
|
| 45 |
-
r = x
|
| 46 |
-
x = self.dw(F.pad(x, (self.pad, 0))).transpose(1, 2)
|
| 47 |
-
x = self.pw2(self.act(self.pw1(self.norm(x))))
|
| 48 |
-
return r + (self.gamma * x).transpose(1, 2)
|
| 49 |
-
|
| 50 |
|
| 51 |
-
|
| 52 |
-
def __init__(self, in_dim, out_dim, factor, kernel=9):
|
| 53 |
-
super().__init__()
|
| 54 |
-
self.factor, self.pad = factor, kernel - 1
|
| 55 |
-
self.conv = nn.Conv1d(in_dim, out_dim, kernel); self.act = nn.GELU()
|
| 56 |
-
|
| 57 |
-
def forward(self, x):
|
| 58 |
-
x = F.interpolate(x, scale_factor=self.factor, mode="linear", align_corners=False)
|
| 59 |
-
return self.act(self.conv(F.pad(x, (self.pad, 0))))
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
class SineGen(nn.Module):
|
| 63 |
-
def __init__(self, samp_rate, harmonic_num=0, sine_amp=0.1, noise_std=0.003, voiced_threshold=0):
|
| 64 |
-
super().__init__()
|
| 65 |
-
self.sine_amp, self.noise_std = sine_amp, noise_std
|
| 66 |
-
self.harmonic_num, self.sampling_rate, self.voiced_threshold = harmonic_num, samp_rate, voiced_threshold
|
| 67 |
-
|
| 68 |
-
@torch.no_grad()
|
| 69 |
-
def forward(self, f0):
|
| 70 |
-
f0 = f0.transpose(1, 2)
|
| 71 |
-
Fm = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1)), device=f0.device)
|
| 72 |
-
for i in range(self.harmonic_num + 1):
|
| 73 |
-
Fm[:, i:i + 1, :] = f0 * (i + 1) / self.sampling_rate
|
| 74 |
-
theta = 2 * np.pi * (torch.cumsum(Fm, dim=-1) % 1)
|
| 75 |
-
phase = Uniform(-np.pi, np.pi).sample((f0.size(0), self.harmonic_num + 1, 1)).to(f0.device)
|
| 76 |
-
phase[:, 0, :] = 0
|
| 77 |
-
sine = self.sine_amp * torch.sin(theta + phase)
|
| 78 |
-
uv = (f0 > self.voiced_threshold).float()
|
| 79 |
-
noise = (uv * self.noise_std + (1 - uv) * self.sine_amp / 3) * torch.randn_like(sine)
|
| 80 |
-
sine = sine * uv + noise
|
| 81 |
-
return sine.transpose(1, 2), uv.transpose(1, 2), noise
|
| 82 |
|
| 83 |
|
| 84 |
-
class SourceModuleHnNSF(nn.Module):
|
| 85 |
-
def __init__(self, sampling_rate, harmonic_num=8, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0):
|
| 86 |
-
super().__init__()
|
| 87 |
-
self.sine_amp = sine_amp
|
| 88 |
-
self.l_sin_gen = SineGen(sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod)
|
| 89 |
-
self.l_linear = nn.Linear(harmonic_num + 1, 1); self.l_tanh = nn.Tanh()
|
| 90 |
-
|
| 91 |
-
def forward(self, f0):
|
| 92 |
-
with torch.no_grad():
|
| 93 |
-
sine_wavs, uv, _ = self.l_sin_gen(f0)
|
| 94 |
-
return self.l_tanh(self.l_linear(sine_wavs)), torch.randn_like(uv) * self.sine_amp / 3, uv
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
class F0Predictor(nn.Module):
|
| 98 |
-
def __init__(self, in_ch=1024, hid=256, k=5, n_layers=4):
|
| 99 |
-
super().__init__()
|
| 100 |
-
self.k = k
|
| 101 |
-
chs = [in_ch] + [hid] * n_layers
|
| 102 |
-
self.convs = nn.ModuleList([nn.Conv1d(chs[i], chs[i + 1], k) for i in range(n_layers)])
|
| 103 |
-
self.out = nn.Conv1d(hid, 1, 1)
|
| 104 |
-
|
| 105 |
-
def forward(self, z):
|
| 106 |
-
x = z
|
| 107 |
-
for c in self.convs:
|
| 108 |
-
x = F.elu(c(F.pad(x, (self.k - 1, 0))))
|
| 109 |
-
return F.softplus(self.out(x)).squeeze(1)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
class NSFHybridDecoder(nn.Module):
|
| 113 |
-
def __init__(self, in_dim=Z86_DIM, dim_low=768, dim_high=512, n_low=8, n_high=3,
|
| 114 |
-
up_factors=(3,), base_hop=279, sr=24000, harmonic_num=8):
|
| 115 |
-
super().__init__()
|
| 116 |
-
U = 1
|
| 117 |
-
for f in up_factors:
|
| 118 |
-
U *= f
|
| 119 |
-
hop = base_hop // U; n_fft = hop * 4
|
| 120 |
-
self.proj = nn.Conv1d(in_dim, dim_low, 1)
|
| 121 |
-
self.low = nn.ModuleList([CausalConvNeXt(dim_low) for _ in range(n_low)])
|
| 122 |
-
self.ups = nn.ModuleList(); d = dim_low
|
| 123 |
-
for i, f in enumerate(up_factors):
|
| 124 |
-
out = dim_high if i == len(up_factors) - 1 else dim_low
|
| 125 |
-
self.ups.append(CausalUpsample(d, out, f)); d = out
|
| 126 |
-
self.high = nn.ModuleList([CausalConvNeXt(dim_high) for _ in range(n_high)])
|
| 127 |
-
self.norm = nn.LayerNorm(dim_high, eps=1e-6)
|
| 128 |
-
self.head = ISTFTHead(dim=dim_high, n_fft=n_fft, hop_length=hop, padding="same")
|
| 129 |
-
self.f0_predictor = F0Predictor(in_ch=in_dim, hid=256)
|
| 130 |
-
self.m_source = SourceModuleHnNSF(sr, harmonic_num=harmonic_num)
|
| 131 |
-
self.low_nfft, self.low_hop = base_hop * 4, base_hop
|
| 132 |
-
self.high_nfft, self.high_hop = n_fft, hop
|
| 133 |
-
self.src_low_proj = nn.Conv1d(self.low_nfft + 2, dim_low, 1)
|
| 134 |
-
self.src_high_proj = nn.Conv1d(self.high_nfft + 2, dim_high, 1)
|
| 135 |
-
self.register_buffer("win_low", torch.hann_window(self.low_nfft), persistent=False)
|
| 136 |
-
self.register_buffer("win_high", torch.hann_window(self.high_nfft), persistent=False)
|
| 137 |
-
self.base_hop = base_hop
|
| 138 |
-
|
| 139 |
-
def _stft(self, x, n_fft, hop, win):
|
| 140 |
-
s = torch.stft(x.float(), n_fft, hop, n_fft, win.float(), center=True, return_complex=True)
|
| 141 |
-
return torch.cat([s.real, s.imag], dim=1)
|
| 142 |
-
|
| 143 |
-
@torch.no_grad()
|
| 144 |
-
def forward(self, z86):
|
| 145 |
-
f0 = self.f0_predictor(z86)
|
| 146 |
-
f0_up = F.interpolate(f0[:, None], scale_factor=self.base_hop, mode="nearest")[:, 0]
|
| 147 |
-
src, _, _ = self.m_source(f0_up[..., None]); src = src.squeeze(-1)
|
| 148 |
-
s_low = self._stft(src, self.low_nfft, self.low_hop, self.win_low)
|
| 149 |
-
s_high = self._stft(src, self.high_nfft, self.high_hop, self.win_high)
|
| 150 |
-
x = self.proj(z86)
|
| 151 |
-
Tm = min(s_low.shape[-1], x.shape[-1])
|
| 152 |
-
x = x[..., :Tm] + self.src_low_proj(s_low[..., :Tm])
|
| 153 |
-
for b in self.low:
|
| 154 |
-
x = b(x)
|
| 155 |
-
for u in self.ups:
|
| 156 |
-
x = u(x)
|
| 157 |
-
Th = min(s_high.shape[-1], x.shape[-1])
|
| 158 |
-
x = x[..., :Th] + self.src_high_proj(s_high[..., :Th])
|
| 159 |
-
for b in self.high:
|
| 160 |
-
x = b(x)
|
| 161 |
-
return self.head(self.norm(x.transpose(1, 2)))
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
# ============================ public wrapper ============================
|
| 165 |
class ECodecFast(nn.Module):
|
| 166 |
-
def __init__(self, bundle_path=None, device="cpu"
|
| 167 |
-
"""
|
| 168 |
-
|
| 169 |
-
Use it when another decoder (nano-NSF v2) renders the audio."""
|
| 170 |
-
if bundle_path is None: # default: ecodec_fast.pth in $ECODEC_WEIGHTS or the repo root
|
| 171 |
-
bundle_path = os.path.join(os.environ.get("ECODEC_WEIGHTS") or
|
| 172 |
-
os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."),
|
| 173 |
-
"ecodec_fast.pth")
|
| 174 |
super().__init__()
|
|
|
|
| 175 |
self.device = device
|
| 176 |
-
self.can_decode = bool(need_decode)
|
| 177 |
ck = torch.load(bundle_path, map_location="cpu", weights_only=False)
|
| 178 |
self.meta = ck.get("meta", {})
|
| 179 |
self.code_sr = self.meta.get("code_sr", 44100) # native ECodec input rate
|
| 180 |
self.out_sr = self.meta.get("out_sr", 24000) # decoder output rate
|
| 181 |
self.n_codebooks = self.meta.get("n_codebooks", 10)
|
| 182 |
-
# native encoder + quantizer (conv decoder intentionally absent)
|
| 183 |
ec = ECodec()
|
| 184 |
ec.load_state_dict({k: v.float() for k, v in ck["codec"].items()}, strict=False)
|
| 185 |
if hasattr(ec, "decoder"):
|
| 186 |
-
del ec.decoder #
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
self.encoder = ec.encoder
|
| 188 |
self.quantizer = ec.quantizer
|
| 189 |
self._ec = ec # keep for ec.encode()
|
| 190 |
-
# compact hybrid decoder (v1)
|
| 191 |
-
if need_decode:
|
| 192 |
-
self.G = NSFHybridDecoder(**ck["cfg"])
|
| 193 |
-
self.G.load_state_dict({k: v.float() for k, v in ck["G"].items()})
|
| 194 |
-
else:
|
| 195 |
-
self.G = None
|
| 196 |
-
# encode is downsample -> pre_module -> quantizers; the decode half
|
| 197 |
-
# is dead weight here.
|
| 198 |
-
self.quantizer.post_module = nn.Identity()
|
| 199 |
-
self.quantizer.upsample = nn.Identity()
|
| 200 |
del ck
|
| 201 |
self.eval().to(device)
|
| 202 |
for p in self.parameters():
|
| 203 |
p.requires_grad_(False)
|
|
|
|
| 204 |
|
| 205 |
# ---------- encode ----------
|
| 206 |
@torch.no_grad()
|
|
@@ -232,29 +87,32 @@ class ECodecFast(nn.Module):
|
|
| 232 |
wav, sr = torchaudio.load(path)
|
| 233 |
return self.encode(wav, sr, chunk_sec)
|
| 234 |
|
| 235 |
-
# ---------- decode ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
@torch.no_grad()
|
| 237 |
-
def decode(self, codes, nq=None):
|
| 238 |
-
"""codes: LongTensor [N, T] or [B, N, T]
|
|
|
|
| 239 |
Returns audio float [L] (or [B, L]) @24kHz in [-1, 1]."""
|
| 240 |
-
if not self.can_decode:
|
| 241 |
-
raise RuntimeError("this ECodecFast was built encode-only "
|
| 242 |
-
"(need_decode=False); use the v2 decoder")
|
| 243 |
if isinstance(codes, np.ndarray):
|
| 244 |
codes = torch.from_numpy(codes)
|
| 245 |
codes = codes.long()
|
| 246 |
squeeze = codes.dim() == 2
|
| 247 |
-
|
| 248 |
-
codes = codes[None] # [1, N, T]
|
| 249 |
-
nq = nq or codes.shape[1]
|
| 250 |
-
codes = codes[:, :nq].to(self.device)
|
| 251 |
-
z86 = self.quantizer.decode(codes) # [B, 1024, T*4] @86Hz
|
| 252 |
-
audio = self.G(z86).clamp(-1, 1) # [B, L] @24kHz
|
| 253 |
-
audio = audio.cpu()
|
| 254 |
return audio[0] if squeeze else audio
|
| 255 |
|
| 256 |
-
def decode_to_file(self, codes, path, nq=None):
|
| 257 |
-
audio = self.decode(codes, nq)
|
| 258 |
if audio.dim() == 1:
|
| 259 |
audio = audio[None]
|
| 260 |
torchaudio.save(path, audio, self.out_sr)
|
|
@@ -262,19 +120,14 @@ class ECodecFast(nn.Module):
|
|
| 262 |
|
| 263 |
if __name__ == "__main__":
|
| 264 |
import argparse
|
| 265 |
-
ap = argparse.ArgumentParser(description="ECodec-
|
| 266 |
-
ap.add_argument("--
|
| 267 |
-
ap.add_argument("--in_wav"); ap.add_argument("--out_wav", default="out.wav")
|
| 268 |
ap.add_argument("--nq", type=int, default=10); ap.add_argument("--device", default="cpu")
|
|
|
|
| 269 |
a = ap.parse_args()
|
| 270 |
-
m = ECodecFast(a.
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
else:
|
| 277 |
-
print("smoke:", end=" ")
|
| 278 |
-
c = torch.randint(0, 1024, (10, 50)); c[0] = torch.randint(0, 4096, (50,))
|
| 279 |
-
w = m.decode(c, nq=a.nq)
|
| 280 |
-
print(f"codes(10,50) -> audio {tuple(w.shape)} ({w.shape[-1]/m.out_sr:.2f}s) finite={torch.isfinite(w).all().item()}")
|
|
|
|
| 1 |
+
"""ECodec-FAST: native ECodec encoder + RVQ, decoded by the binned-F0 nano-NSF v2 decoder.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
codec: ECodec 44.1kHz, RVQ 10 codebooks @21.53Hz (cb0 semantic 4096 + 9 residual 1024)
|
| 4 |
+
encode: audio -> ECodec encoder -> RVQ codes [10, T]
|
| 5 |
+
decode: codes -> quantizer front-end (from_codes + distilled post-VQ + upsample) -> z86 @86Hz
|
| 6 |
+
-> NSF decoder with binned F0 (stable pitch) -> 24kHz
|
| 7 |
|
| 8 |
Usage:
|
| 9 |
+
from ecodec_fast import ECodecFast
|
| 10 |
m = ECodecFast() # weights from the repo root, cpu by default
|
| 11 |
codes = m.encode_file("in.wav") # -> LongTensor [10, T]
|
| 12 |
+
m.decode_to_file(codes, "out.wav") # -> 24kHz wav
|
| 13 |
|
| 14 |
+
Weights: ecodec_encoder.pth (encoder + quantizer, fp16 on disk, run in fp32) and, for decoding,
|
| 15 |
+
nano_nsf_v2_60k.pt + postvq_student_90k.pt + ecodec_quantizer_slim.pt (see decoder.py).
|
|
|
|
| 16 |
"""
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
import torchaudio
|
|
|
|
| 24 |
|
| 25 |
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # local ECodec class defs
|
| 26 |
+
from ecodec import ECodec # noqa: E402
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
_ROOT = os.environ.get("ECODEC_WEIGHTS") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
class ECodecFast(nn.Module):
|
| 32 |
+
def __init__(self, bundle_path=None, device="cpu"):
|
| 33 |
+
"""bundle_path: encoder weights (default: ecodec_encoder.pth in $ECODEC_WEIGHTS or the repo root).
|
| 34 |
+
The decoder is loaded lazily on the first decode() call."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
super().__init__()
|
| 36 |
+
bundle_path = bundle_path or os.path.join(_ROOT, "ecodec_encoder.pth")
|
| 37 |
self.device = device
|
|
|
|
| 38 |
ck = torch.load(bundle_path, map_location="cpu", weights_only=False)
|
| 39 |
self.meta = ck.get("meta", {})
|
| 40 |
self.code_sr = self.meta.get("code_sr", 44100) # native ECodec input rate
|
| 41 |
self.out_sr = self.meta.get("out_sr", 24000) # decoder output rate
|
| 42 |
self.n_codebooks = self.meta.get("n_codebooks", 10)
|
|
|
|
| 43 |
ec = ECodec()
|
| 44 |
ec.load_state_dict({k: v.float() for k, v in ck["codec"].items()}, strict=False)
|
| 45 |
if hasattr(ec, "decoder"):
|
| 46 |
+
del ec.decoder # original 54M conv decoder: unused
|
| 47 |
+
# encode is downsample -> pre_module -> quantizers; the decode half is not needed here
|
| 48 |
+
# (the v2 decoder carries its own slim front-end).
|
| 49 |
+
ec.quantizer.post_module = nn.Identity()
|
| 50 |
+
ec.quantizer.upsample = nn.Identity()
|
| 51 |
self.encoder = ec.encoder
|
| 52 |
self.quantizer = ec.quantizer
|
| 53 |
self._ec = ec # keep for ec.encode()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
del ck
|
| 55 |
self.eval().to(device)
|
| 56 |
for p in self.parameters():
|
| 57 |
p.requires_grad_(False)
|
| 58 |
+
self._decoder = None
|
| 59 |
|
| 60 |
# ---------- encode ----------
|
| 61 |
@torch.no_grad()
|
|
|
|
| 87 |
wav, sr = torchaudio.load(path)
|
| 88 |
return self.encode(wav, sr, chunk_sec)
|
| 89 |
|
| 90 |
+
# ---------- decode (binned-F0 nano-NSF v2) ----------
|
| 91 |
+
@property
|
| 92 |
+
def decoder(self):
|
| 93 |
+
if self._decoder is None:
|
| 94 |
+
from decoder import NanoDecoderV2
|
| 95 |
+
self._decoder = NanoDecoderV2(device=self.device)
|
| 96 |
+
return self._decoder
|
| 97 |
+
|
| 98 |
+
def speaker_ref(self, wav, sr=None):
|
| 99 |
+
"""Speaker prompt -> pitch statistics for decode(ref=...). Needs torchcrepe."""
|
| 100 |
+
return self.decoder.speaker_ref(wav, sr)
|
| 101 |
+
|
| 102 |
@torch.no_grad()
|
| 103 |
+
def decode(self, codes, nq=None, ref=None, ref_strength=3.0):
|
| 104 |
+
"""codes: LongTensor [N, T] or [B, N, T]; nq: codebooks to use (>=3, default all).
|
| 105 |
+
ref=None: pitch predicted from the codes; ref=speaker_ref(...): pitch anchored to that speaker.
|
| 106 |
Returns audio float [L] (or [B, L]) @24kHz in [-1, 1]."""
|
|
|
|
|
|
|
|
|
|
| 107 |
if isinstance(codes, np.ndarray):
|
| 108 |
codes = torch.from_numpy(codes)
|
| 109 |
codes = codes.long()
|
| 110 |
squeeze = codes.dim() == 2
|
| 111 |
+
audio = self.decoder.from_codes(codes, nq=nq, ref=ref, ref_strength=ref_strength).cpu()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
return audio[0] if squeeze else audio
|
| 113 |
|
| 114 |
+
def decode_to_file(self, codes, path, nq=None, ref=None):
|
| 115 |
+
audio = self.decode(codes, nq, ref)
|
| 116 |
if audio.dim() == 1:
|
| 117 |
audio = audio[None]
|
| 118 |
torchaudio.save(path, audio, self.out_sr)
|
|
|
|
| 120 |
|
| 121 |
if __name__ == "__main__":
|
| 122 |
import argparse
|
| 123 |
+
ap = argparse.ArgumentParser(description="ECodec-FAST encode/decode")
|
| 124 |
+
ap.add_argument("--in_wav", required=True); ap.add_argument("--out_wav", default="out.wav")
|
|
|
|
| 125 |
ap.add_argument("--nq", type=int, default=10); ap.add_argument("--device", default="cpu")
|
| 126 |
+
ap.add_argument("--speaker_ref", help="optional speaker prompt to anchor pitch (needs torchcrepe)")
|
| 127 |
a = ap.parse_args()
|
| 128 |
+
m = ECodecFast(device=a.device)
|
| 129 |
+
c = m.encode_file(a.in_wav)
|
| 130 |
+
print(f"encoded -> codes {tuple(c.shape)} (cb0 uniq {len(c[0].unique())})")
|
| 131 |
+
ref = m.speaker_ref(a.speaker_ref) if a.speaker_ref else None
|
| 132 |
+
m.decode_to_file(c, a.out_wav, nq=a.nq, ref=ref)
|
| 133 |
+
print(f"decoded nq{a.nq} -> {a.out_wav} @{m.out_sr}Hz")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|