ECodec-FAST / ecodec_fast /nano_core.py
Den4ikAI's picture
ECodec-FAST: codec extracted from ESpeech-V9-ECodec-FAST v2
0981df7 verified
Raw History Blame Contribute Delete
7.7 kB
"""Core pieces of the ECodec-nano decoder (extracted from the training tree for deployment).
Front-end (frozen, reused from ECodec): codes[:N] -> z86 latent [B,1024,T] @86.13Hz
via the trained, checkerboard-safe (k=stride) DownsampleRVQ.decode (from_codes + upsample).
Backbone: causal ConvNeXt on the frame rate; synthesis is a fixed iSTFT (no conv-to-waveform).
Rates: ECodec code rate 21.53Hz -> upsample x4 -> z86 86.13Hz -> iSTFT hop 279 -> ~24k.
"""
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
_HERE = os.path.dirname(os.path.abspath(__file__))
ECODEC_ROOT = _HERE # ECodec class defs live next to this file
_MODELS = os.environ.get("ECODEC_WEIGHTS") or os.path.join(_HERE, "..") # repo root by default
# With the distilled post_module the quantizer bundle no longer needs the 417 MB
# teacher, so the slim file (81 MB) is preferred when present.
ECODEC_CKPT = os.environ.get("ESP_QUANTIZER") or next(
(p for p in (os.path.join(_MODELS, "ecodec_quantizer_slim.pt"),
os.path.join(_MODELS, "ecodec_quantizer.pt")) if os.path.exists(p)),
os.path.join(_MODELS, "ecodec_quantizer.pt"))
Z86_DIM = 1024
class CausalConvNeXt(nn.Module):
"""Causal ConvNeXt block: left-padded depthwise conv + pointwise MLP."""
def __init__(self, dim: int, kernel: int = 7, mult: int = 3):
super().__init__()
self.pad = kernel - 1
self.dw = nn.Conv1d(dim, dim, kernel, groups=dim)
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.pw1 = nn.Linear(dim, dim * mult)
self.act = nn.GELU()
self.pw2 = nn.Linear(dim * mult, dim)
self.gamma = nn.Parameter(1e-6 * torch.ones(dim))
def forward(self, x): # x [B,C,T]
r = x
x = self.dw(F.pad(x, (self.pad, 0))) # causal: left-pad only
x = x.transpose(1, 2)
x = self.pw2(self.act(self.pw1(self.norm(x))))
x = (self.gamma * x).transpose(1, 2)
return r + x
class _PostVQStudent(nn.Module):
"""Distilled post_module: matches the teacher's `z_q -> z_q` interface.
The student is conditioned on the codebook count, so it is told how many
codebooks the request actually used.
"""
def __init__(self, net, nq: int = 9):
super().__init__()
self.net = net
self.nq = nq
def forward(self, z_q):
return self.net(z_q, nq=self.nq)[0]
def _default_student():
p = os.path.join(_MODELS, "postvq_student_90k.pt")
return p if os.path.exists(p) else None
def _load_postvq_student(ckpt: str):
sys.path.insert(0, _HERE) if _HERE not in sys.path else None
from postvq_student import StudentTransformer # noqa: E402
ck = torch.load(ckpt, map_location="cpu", weights_only=False, mmap=True)
cfg = ck.get("cfg") or {}
net = StudentTransformer(**cfg) if isinstance(cfg, dict) else StudentTransformer()
try:
net.load_state_dict(ck["student"], assign=True)
except TypeError:
net.load_state_dict(ck["student"])
net.eval()
return _PostVQStudent(net)
class ECodecFrontend(nn.Module):
"""Frozen: codes[:N] -> z86 [B,1024,T86]. Reuses ECodec's trained from_codes+upsample.
Production: loads the slim decode-side quantizer weights (post_module + upsample
+ codebooks, ~500 MB) instead of the full 1.9 GB ECodec checkpoint. The tensors
are the ones the v2 decoder was trained against, so output is bit-identical.
"""
def __init__(self, ckpt: str = ECODEC_CKPT, ecodec_root: str = ECODEC_ROOT,
dtype: torch.dtype | None = None):
super().__init__()
if ecodec_root not in sys.path:
sys.path.insert(0, ecodec_root)
from ecodec import DownsampleResidualVectorQuantize, WindowLimitedTransformer
# Decode is `from_codes -> post_module -> upsample`; the encode-side
# pre_module (417 MB) and downsample (80 MB) are never touched, and
# building the surrounding ECodec would also allocate the encoder and
# the 54M conv decoder. Construct just the quantizer and stub out the
# encode half, so nothing unused is ever allocated.
#
# post_module is the 109M teacher transformer (417 MB). ESP_POSTVQ=student
# swaps in the distilled 14.7M student (56 MB) — validated as perceptually
# equivalent; see FINDINGS §3 in the ECodec-nano tree.
student_ckpt = os.environ.get("ESP_POSTVQ_CKPT") or _default_student()
self.postvq = "teacher"
self._teacher_preloaded = False
if os.environ.get("ESP_POSTVQ", "student") == "student" and student_ckpt:
q_post = _load_postvq_student(student_ckpt)
self.postvq = "student"
else:
q_post = WindowLimitedTransformer(
n_layer=8, n_head=16, dim=1024, intermediate_size=3072,
head_dim=64, block_size=4096, dropout_rate=0.1, attn_dropout_rate=0.1,
input_dim=1024, window_size=128, causal=True, channels_first=True)
tw = os.environ.get("ESP_POSTVQ_TEACHER") or os.path.join(
_MODELS, "postvq_teacher.pt")
if os.path.exists(tw): # standalone teacher weights
tsd = torch.load(tw, map_location="cpu", weights_only=False, mmap=True)
try:
q_post.load_state_dict(tsd, assign=True)
except TypeError:
q_post.load_state_dict(tsd)
self._teacher_preloaded = True
q = DownsampleResidualVectorQuantize(
input_dim=1024, n_codebooks=9, codebook_dim=8, quantizer_dropout=0.5,
codebook_size=1024, semantic_codebook_size=4096,
downsample_factor=(2, 2), pre_module=None, post_module=q_post)
q.pre_module = nn.Identity()
q.downsample = nn.Identity()
# mmap + assign: the weights stay file-backed instead of being copied into
# anonymous memory, so the kernel can evict them under pressure and several
# worker processes share one copy.
drop = ["pre_module.", "downsample."]
if self.postvq == "student" or self._teacher_preloaded:
drop.append("post_module.") # already carries its own weights
sd = torch.load(ckpt, map_location="cpu", weights_only=False, mmap=True)
sd = {k: v for k, v in sd.items() if not k.startswith(tuple(drop))}
try:
missing, unexpected = q.load_state_dict(sd, strict=False, assign=True)
except TypeError: # torch < 2.1: no assign=
missing, unexpected = q.load_state_dict(sd, strict=False)
# `in_proj` lives on the encode side (decode goes through out_proj), so
# its absence from the slim bundle is expected.
needed = ["upsample.", "quantizer.", "semantic_quantizer."]
if self.postvq == "teacher" and not self._teacher_preloaded:
needed.append("post_module.")
blocking = [k for k in missing
if "in_proj" not in k and k.startswith(tuple(needed))]
if blocking:
raise RuntimeError(f"quantizer weights missing: {blocking[:4]} "
f"(+{len(blocking) - 4} more)")
self.quantizer = q
if dtype is not None:
self.quantizer.to(dtype)
for p in self.parameters():
p.requires_grad_(False)
self.eval()
@torch.no_grad()
def forward(self, codes): # codes [B,N,T] long (N<=10)
return self.quantizer.decode(codes) # z86 [B,1024, T*4]