ECodec-FAST / ecodec_fast /codec_fast.py
Den4ikAI's picture
Binned-F0 decoder only: drop v1 decoder, encoder-only checkpoint
52c4f4a verified
Raw History Blame Contribute Delete
6.16 kB
"""ECodec-FAST: native ECodec encoder + RVQ, decoded by the binned-F0 nano-NSF v2 decoder.
codec: ECodec 44.1kHz, RVQ 10 codebooks @21.53Hz (cb0 semantic 4096 + 9 residual 1024)
encode: audio -> ECodec encoder -> RVQ codes [10, T]
decode: codes -> quantizer front-end (from_codes + distilled post-VQ + upsample) -> z86 @86Hz
-> NSF decoder with binned F0 (stable pitch) -> 24kHz
Usage:
from ecodec_fast import ECodecFast
m = ECodecFast() # weights from the repo root, cpu by default
codes = m.encode_file("in.wav") # -> LongTensor [10, T]
m.decode_to_file(codes, "out.wav") # -> 24kHz wav
Weights: ecodec_encoder.pth (encoder + quantizer, fp16 on disk, run in fp32) and, for decoding,
nano_nsf_v2_60k.pt + postvq_student_90k.pt + ecodec_quantizer_slim.pt (see decoder.py).
"""
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torchaudio
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # local ECodec class defs
from ecodec import ECodec # noqa: E402
_ROOT = os.environ.get("ECODEC_WEIGHTS") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
class ECodecFast(nn.Module):
def __init__(self, bundle_path=None, device="cpu"):
"""bundle_path: encoder weights (default: ecodec_encoder.pth in $ECODEC_WEIGHTS or the repo root).
The decoder is loaded lazily on the first decode() call."""
super().__init__()
bundle_path = bundle_path or os.path.join(_ROOT, "ecodec_encoder.pth")
self.device = device
ck = torch.load(bundle_path, map_location="cpu", weights_only=False)
self.meta = ck.get("meta", {})
self.code_sr = self.meta.get("code_sr", 44100) # native ECodec input rate
self.out_sr = self.meta.get("out_sr", 24000) # decoder output rate
self.n_codebooks = self.meta.get("n_codebooks", 10)
ec = ECodec()
ec.load_state_dict({k: v.float() for k, v in ck["codec"].items()}, strict=False)
if hasattr(ec, "decoder"):
del ec.decoder # original 54M conv decoder: unused
# encode is downsample -> pre_module -> quantizers; the decode half is not needed here
# (the v2 decoder carries its own slim front-end).
ec.quantizer.post_module = nn.Identity()
ec.quantizer.upsample = nn.Identity()
self.encoder = ec.encoder
self.quantizer = ec.quantizer
self._ec = ec # keep for ec.encode()
del ck
self.eval().to(device)
for p in self.parameters():
p.requires_grad_(False)
self._decoder = None
# ---------- encode ----------
@torch.no_grad()
def encode(self, wav, sr, chunk_sec=5.0):
"""wav: [L] or [C,L] tensor/np @sr. Returns codes LongTensor [10, T].
Chunks to <=chunk_sec BEFORE encoding — long/clipped inputs otherwise collapse
the encoder (cb0 -> a single index -> silence). The decoder handles long inputs fine,
so per-chunk codes are simply concatenated and decoded in one pass (seamless)."""
if isinstance(wav, np.ndarray):
wav = torch.from_numpy(wav)
wav = wav.float()
if wav.dim() == 1:
wav = wav[None]
wav = wav.mean(0, keepdim=True) # mono [1, L]
if sr != self.code_sr:
wav = torchaudio.functional.resample(wav, sr, self.code_sr)
wav = wav.to(self.device)
ch = int(chunk_sec * self.code_sr)
parts = []
for s in range(0, wav.shape[1], ch):
seg = wav[:, s:s + ch]
if seg.shape[1] < self.code_sr * 0.1:
continue
codes, _ = self._ec.encode(seg[None]) # [1, 10, Tc]
parts.append(codes[0])
return torch.cat(parts, dim=1).long().cpu() # [10, T]
def encode_file(self, path, chunk_sec=5.0):
wav, sr = torchaudio.load(path)
return self.encode(wav, sr, chunk_sec)
# ---------- decode (binned-F0 nano-NSF v2) ----------
@property
def decoder(self):
if self._decoder is None:
from decoder import NanoDecoderV2
self._decoder = NanoDecoderV2(device=self.device)
return self._decoder
def speaker_ref(self, wav, sr=None):
"""Speaker prompt -> pitch statistics for decode(ref=...). Needs torchcrepe."""
return self.decoder.speaker_ref(wav, sr)
@torch.no_grad()
def decode(self, codes, nq=None, ref=None, ref_strength=3.0):
"""codes: LongTensor [N, T] or [B, N, T]; nq: codebooks to use (>=3, default all).
ref=None: pitch predicted from the codes; ref=speaker_ref(...): pitch anchored to that speaker.
Returns audio float [L] (or [B, L]) @24kHz in [-1, 1]."""
if isinstance(codes, np.ndarray):
codes = torch.from_numpy(codes)
codes = codes.long()
squeeze = codes.dim() == 2
audio = self.decoder.from_codes(codes, nq=nq, ref=ref, ref_strength=ref_strength).cpu()
return audio[0] if squeeze else audio
def decode_to_file(self, codes, path, nq=None, ref=None):
audio = self.decode(codes, nq, ref)
if audio.dim() == 1:
audio = audio[None]
torchaudio.save(path, audio, self.out_sr)
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser(description="ECodec-FAST encode/decode")
ap.add_argument("--in_wav", required=True); ap.add_argument("--out_wav", default="out.wav")
ap.add_argument("--nq", type=int, default=10); ap.add_argument("--device", default="cpu")
ap.add_argument("--speaker_ref", help="optional speaker prompt to anchor pitch (needs torchcrepe)")
a = ap.parse_args()
m = ECodecFast(device=a.device)
c = m.encode_file(a.in_wav)
print(f"encoded -> codes {tuple(c.shape)} (cb0 uniq {len(c[0].unique())})")
ref = m.speaker_ref(a.speaker_ref) if a.speaker_ref else None
m.decode_to_file(c, a.out_wav, nq=a.nq, ref=ref)
print(f"decoded nq{a.nq} -> {a.out_wav} @{m.out_sr}Hz")