Den4ikAI commited on
Commit
0981df7
·
verified ·
1 Parent(s): d0ddc6d

ECodec-FAST: codec extracted from ESpeech-V9-ECodec-FAST v2

Browse files
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - ru
5
+ pipeline_tag: audio-to-audio
6
+ tags:
7
+ - audio
8
+ - codec
9
+ - neural-audio-codec
10
+ - speech
11
+ - espeech
12
+ ---
13
+
14
+ # ECodec-FAST
15
+
16
+ Нейросетевой аудиокодек из [ESpeech-V9-ECodec-FAST](https://huggingface.co/ESpeech/ESpeech-V9-ECodec-FAST), вынесенный
17
+ отдельно от TTS: родной энкодер и квантайзер ECodec плюс два быстрых декодера, работающих на CPU.
18
+
19
+ ```
20
+ аудио 44.1 кГц ─► энкодер ECodec ─► RVQ: 10 кодбуков @ 21.53 Гц
21
+ (cb0 семантический, 4096; cb1..cb9 — 1024)
22
+ коды ─► декодер v1 (NSF-hybrid iSTFT, 41M) ─► 24 кГц
23
+ коды ─► декодер v2 (дистиллят post-VQ 14.7M + nano-NSF, binned F0) ─► 24 кГц
24
+ ```
25
+
26
+ | | |
27
+ |---|---|
28
+ | вход | 44.1 кГц, моно (другие частоты ресемплируются) |
29
+ | выход | 24 кГц, моно |
30
+ | коды | `LongTensor [10, T]`, 21.53 кадра/с |
31
+ | декодирование | каузальное, стримится чанками |
32
+
33
+ ## Файлы
34
+
35
+ | файл | размер | что |
36
+ |---|---|---|
37
+ | `ecodec_fast.pth` | 760 МБ | энкодер + квантайзер ECodec + декодер v1 (fp16 на диске, считается в fp32) |
38
+ | `nano_nsf_v2_60k.pt` | 181 МБ | декодер v2 (NSF, binned F0) |
39
+ | `postvq_student_90k.pt` | 56 МБ | дистиллированный post-VQ для v2 |
40
+ | `ecodec_quantizer_slim.pt` | 81 МБ | кодбуки + upsample для фронтенда v2 |
41
+ | `ecodec_fast/` | — | код (без внешних зависимостей, кроме torch/torchaudio/numpy) |
42
+
43
+ ## Быстрый старт
44
+
45
+ ```bash
46
+ huggingface-cli download ESpeech/ECodec-FAST --local-dir ECodec-FAST
47
+ cd ECodec-FAST && pip install -r requirements.txt
48
+ ```
49
+
50
+ ```python
51
+ import torchaudio
52
+ from ecodec_fast import ECodecFast, NanoDecoderV2
53
+
54
+ codec = ECodecFast() # веса из корня репо (или $ECODEC_WEIGHTS), device="cpu"
55
+ codes = codec.encode_file("in.wav") # LongTensor [10, T] @ 21.53 Гц
56
+
57
+ # декодер v1 (идёт в комплекте с ecodec_fast.pth)
58
+ audio = codec.decode(codes) # [L] @ 24 кГц
59
+ torchaudio.save("out_v1.wav", audio[None], 24000)
60
+
61
+ # декодер v2: легче и быстрее
62
+ dec = NanoDecoderV2()
63
+ audio = dec.from_codes(codes) # режим A: питч предсказывается по кодам
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
+ Если нужен только энкодер, `ECodecFast(need_decode=False)` не грузит декодерную часть (~650 МБ экономии).
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=<путь>` — декодер v2 с исходным post-VQ (учитель, 109M; в этот репо не входит).
77
+
78
+ ## Заметки
79
+
80
+ * Выход совпадает с прод-сборкой ESpeech-V9-ECodec-FAST v2 бит-в-бит (проверено на кодах и на обоих декодерах).
81
+ * `ISTFTHead` взят из [vocos](https://github.com/gemelo-ai/vocos) (MIT) и вшит в `ecodec_fast/istft_head.py`, чтобы не тянуть
82
+ vocos и encodec.
ecodec_fast.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:701b086ea43b30e7babc29eb1daedd173f01bfda88a4d43736abfc335877a13c
3
+ size 759998080
ecodec_fast/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ECodec-FAST: ECodec 44.1 kHz encoder + RVQ (10 codebooks @21.53 Hz) with fast 24 kHz decoders.
2
+
3
+ from ecodec_fast import ECodecFast, NanoDecoderV2
4
+ """
5
+ import os as _os
6
+ import sys as _sys
7
+
8
+ _HERE = _os.path.dirname(_os.path.abspath(__file__))
9
+ if _HERE not in _sys.path: # the modules import each other by bare name
10
+ _sys.path.insert(0, _HERE)
11
+
12
+ from codec_fast import ECodecFast # noqa: E402
13
+ from decoder import NanoDecoderV2 # noqa: E402
14
+
15
+ __all__ = ["ECodecFast", "NanoDecoderV2"]
ecodec_fast/codec_fast.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ECodec-fast — production codec bundle.
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
+ decode: codes -> quantizer(from_codes + post_module + upsample) -> z86 @86Hz
9
+ -> NSFHybridDecoder (learned upsampler + NSF source + small iSTFT) -> 24kHz
10
+
11
+ Usage:
12
+ from ecodec_fast import ECodecFast # package import
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", nq=10) # -> 24kHz wav
16
+
17
+ Dependencies: the bundled ECodec class definitions (./ecodec.py) and
18
+ a vendored copy of vocos' ISTFTHead (./istft_head.py). All *weights* live in the
19
+ single ecodec_fast.pth (fp16 on disk, run in fp32).
20
+ """
21
+ import os, sys, math
22
+ import numpy as np
23
+ import torch, torch.nn as nn, torch.nn.functional as F
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
+ class CausalUpsample(nn.Module):
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", need_decode=True):
167
+ """need_decode=False keeps only the encode path (audio -> codes), freeing
168
+ ~650 MB: the decode-side post_module + upsample and the v1 decoder G.
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 # unused: replaced by our G
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()
207
+ def encode(self, wav, sr, chunk_sec=5.0):
208
+ """wav: [L] or [C,L] tensor/np @sr. Returns codes LongTensor [10, T].
209
+ Chunks to <=chunk_sec BEFORE encoding — long/clipped inputs otherwise collapse
210
+ the encoder (cb0 -> a single index -> silence). The decoder handles long inputs fine,
211
+ so per-chunk codes are simply concatenated and decoded in one pass (seamless)."""
212
+ if isinstance(wav, np.ndarray):
213
+ wav = torch.from_numpy(wav)
214
+ wav = wav.float()
215
+ if wav.dim() == 1:
216
+ wav = wav[None]
217
+ wav = wav.mean(0, keepdim=True) # mono [1, L]
218
+ if sr != self.code_sr:
219
+ wav = torchaudio.functional.resample(wav, sr, self.code_sr)
220
+ wav = wav.to(self.device)
221
+ ch = int(chunk_sec * self.code_sr)
222
+ parts = []
223
+ for s in range(0, wav.shape[1], ch):
224
+ seg = wav[:, s:s + ch]
225
+ if seg.shape[1] < self.code_sr * 0.1:
226
+ continue
227
+ codes, _ = self._ec.encode(seg[None]) # [1, 10, Tc]
228
+ parts.append(codes[0])
229
+ return torch.cat(parts, dim=1).long().cpu() # [10, T]
230
+
231
+ def encode_file(self, path, chunk_sec=5.0):
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]. nq: number of codebooks to use (<=N, default all).
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
+ if squeeze:
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)
261
+
262
+
263
+ if __name__ == "__main__":
264
+ import argparse
265
+ ap = argparse.ArgumentParser(description="ECodec-fast encode/decode")
266
+ ap.add_argument("--bundle", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "ecodec_fast.pth"))
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.bundle, a.device)
271
+ if a.in_wav:
272
+ c = m.encode_file(a.in_wav)
273
+ print(f"encoded -> codes {tuple(c.shape)} (cb0 uniq {len(c[0].unique())})")
274
+ m.decode_to_file(c, a.out_wav, nq=a.nq)
275
+ print(f"decoded nq{a.nq} -> {a.out_wav} @{m.out_sr}Hz")
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()}")
ecodec_fast/decoder.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public inference API for the ECodec-nano NSF decoder (binned-F0, v2).
2
+
3
+ from decoder import NanoDecoderV2
4
+
5
+ dec = NanoDecoderV2() # loads weights + frozen ECodec front-end
6
+ audio = dec.from_codes(codes) # MODE A: free-running pitch
7
+ ref = dec.speaker_ref("prompt.wav") # MODE B: anchor pitch to a speaker
8
+ audio = dec.from_codes(codes, ref=ref)
9
+
10
+ See README.md for what the two modes are for.
11
+ """
12
+ import os
13
+ import sys
14
+ import torch
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from nano_core import ECodecFrontend # noqa: E402
18
+ from model_nsf_v2 import NSFNanoDecoderV2 # noqa: E402
19
+ from nsf_source import F0BinnedPredictor # noqa: E402
20
+
21
+ WEIGHTS = os.path.join(os.environ.get("ECODEC_WEIGHTS") or os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."), "nano_nsf_v2_60k.pt")
22
+ OUT_SR = 24000
23
+ MIN_NQ = 3 # below this the F0 predictor loses voicing (nq1 = 0% voiced, see README)
24
+
25
+
26
+ class NanoDecoderV2:
27
+ """codes [B,N,T] @21.53Hz -> 24kHz audio. Causal/streamable; N in 1..10 (use >=3)."""
28
+
29
+ def __init__(self, weights: str = WEIGHTS, device: str = "cpu", threads: int | None = None):
30
+ if threads:
31
+ torch.set_num_threads(threads)
32
+ # mmap + assign keeps the weights file-backed (evictable, shared between
33
+ # worker processes) instead of copying them into anonymous memory.
34
+ ck = torch.load(weights, map_location="cpu", weights_only=False, mmap=True)
35
+ self.device = device
36
+ self.G = NSFNanoDecoderV2(dim=ck.get("dim", 768), n_blocks=ck.get("n_blocks", 12))
37
+ try:
38
+ self.G.load_state_dict(ck["G"], assign=True)
39
+ except TypeError: # torch < 2.1
40
+ self.G.load_state_dict(ck["G"])
41
+ self.G.eval().to(device)
42
+ self.fe = ECodecFrontend().eval().to(device)
43
+ self.meta = {k: v for k, v in ck.items() if k != "G"}
44
+
45
+ # ---- MODE B helper: speaker reference -------------------------------------------------
46
+ def speaker_ref(self, wav, sr: int | None = None):
47
+ """Speaker prompt -> (log-F0 mean, std), to be passed as `ref`. Accepts a path or a tensor.
48
+ Computed once per speaker; needs torchcrepe (only for this call, not for decoding)."""
49
+ if isinstance(wav, str):
50
+ import torchaudio
51
+ wav, sr = torchaudio.load(wav)
52
+ assert sr is not None, "sr required when passing a tensor"
53
+ return F0BinnedPredictor.ref_stats_from_wav(wav, sr, device=self.device)
54
+
55
+ # ---- decoding --------------------------------------------------------------------------
56
+ @torch.no_grad()
57
+ def from_codes(self, codes, nq: int | None = None, ref=None, ref_strength: float = 3.0,
58
+ return_f0: bool = False):
59
+ """codes [B,N,T] long -> audio [B,L] @24kHz.
60
+ ref=None -> MODE A (free-running pitch, predicted from the codes alone)
61
+ ref=speaker_ref(..) -> MODE B (pitch anchored to that speaker's range)"""
62
+ if codes.dim() == 2:
63
+ codes = codes[None]
64
+ if nq is not None:
65
+ codes = codes[:, :nq]
66
+ if codes.shape[1] < MIN_NQ:
67
+ print(f"warning: nq={codes.shape[1]} < {MIN_NQ}; voiced frames collapse (nq1 -> whisper)",
68
+ file=sys.stderr)
69
+ z86 = self.fe(codes.to(self.device))
70
+ out = self.G(z86, return_f0=return_f0, ref_stats=ref,
71
+ prior_strength=(ref_strength if ref is not None else 0.0))
72
+ if return_f0:
73
+ audio, _, f0 = out
74
+ return audio.clamp(-1, 1), f0
75
+ return out.clamp(-1, 1)
76
+
77
+ @torch.no_grad()
78
+ def from_z86(self, z86, ref=None, ref_strength: float = 3.0):
79
+ """Latent [B,1024,T] @86.13Hz -> audio. For when the front-end already ran upstream."""
80
+ return self.G(z86.to(self.device), ref_stats=ref,
81
+ prior_strength=(ref_strength if ref is not None else 0.0)).clamp(-1, 1)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ import glob
86
+ import numpy as np
87
+ import torchaudio
88
+ dec = NanoDecoderV2(threads=8)
89
+ print(f"loaded {dec.meta.get('arch')} @step{dec.meta.get('step')} | "
90
+ f"{sum(p.numel() for p in dec.G.parameters())/1e6:.2f}M | out {OUT_SR}Hz")
91
+ import sys as _s
92
+ codes = torch.from_numpy(np.load(_s.argv[1])[:10].astype(np.int64))
93
+ a = dec.from_codes(codes)
94
+ torchaudio.save("prod_smoke.wav", a.cpu(), OUT_SR)
95
+ print(f"MODE A ok: {tuple(a.shape)} -> prod_smoke.wav ({a.shape[-1]/OUT_SR:.2f}s)")
ecodec_fast/ecodec.py ADDED
@@ -0,0 +1,1211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ECodec: Standalone DAC-based VQVAE audio codec.
3
+
4
+ No external dependencies beyond torch. All utilities are inlined.
5
+ Compatible with ecodec/codec.pth checkpoint.
6
+
7
+ Architecture:
8
+ Encoder: Conv1d(1,64) -> 4 EncoderBlocks [2,4,8,8] -> Conv1d(1024,1024)
9
+ Quantizer: downsample [2,2] -> pre_module (8-layer transformer) ->
10
+ semantic VQ (1 codebook, 4096) + residual VQ (9 codebooks, 1024)
11
+ -> post_module (8-layer transformer) -> upsample [2,2]
12
+ Decoder: Conv1d(1024,1536) -> 4 DecoderBlocks [8,8,4,2] -> Conv1d(96,1) -> Tanh
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import typing as tp
19
+ from contextlib import nullcontext
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from torch import Tensor
26
+ from torch.nn.utils.parametrizations import weight_norm as new_weight_norm
27
+ from torch.nn.utils.parametrize import remove_parametrizations
28
+ from torch.nn.utils import weight_norm as old_weight_norm
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Utility functions
32
+ # ---------------------------------------------------------------------------
33
+
34
+
35
+ def find_multiple(n: int, k: int) -> int:
36
+ if n % k == 0:
37
+ return n
38
+ return n + k - (n % k)
39
+
40
+
41
+ def unpad1d(x: Tensor, paddings: tp.Tuple[int, int]) -> Tensor:
42
+ padding_left, padding_right = paddings
43
+ assert padding_left >= 0 and padding_right >= 0
44
+ assert (padding_left + padding_right) <= x.shape[-1]
45
+ end = x.shape[-1] - padding_right
46
+ return x[..., padding_left:end]
47
+
48
+
49
+ def get_extra_padding_for_conv1d(
50
+ x: Tensor, kernel_size: int, stride: int, padding_total: int = 0
51
+ ) -> int:
52
+ length = x.shape[-1]
53
+ n_frames = (length - kernel_size + padding_total) / stride + 1
54
+ ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
55
+ return ideal_length - length
56
+
57
+
58
+ def pad1d(
59
+ x: Tensor,
60
+ paddings: tp.Tuple[int, int],
61
+ mode: str = "zeros",
62
+ value: float = 0.0,
63
+ ) -> Tensor:
64
+ length = x.shape[-1]
65
+ padding_left, padding_right = paddings
66
+ assert padding_left >= 0 and padding_right >= 0
67
+ if mode == "reflect":
68
+ max_pad = max(padding_left, padding_right)
69
+ extra_pad = 0
70
+ if length <= max_pad:
71
+ extra_pad = max_pad - length + 1
72
+ x = F.pad(x, (0, extra_pad))
73
+ padded = F.pad(x, paddings, mode, value)
74
+ end = padded.shape[-1] - extra_pad
75
+ return padded[..., :end]
76
+ else:
77
+ return F.pad(x, paddings, mode, value)
78
+
79
+
80
+ def precompute_freqs_cis(
81
+ seq_len: int, n_elem: int, base: int = 10000, dtype: torch.dtype = torch.bfloat16
82
+ ) -> Tensor:
83
+ freqs = 1.0 / (
84
+ base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)
85
+ )
86
+ t = torch.arange(seq_len, device=freqs.device)
87
+ freqs = torch.outer(t, freqs)
88
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
89
+ cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
90
+ return cache.to(dtype=dtype)
91
+
92
+
93
+ def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
94
+ xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
95
+ freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
96
+ x_out2 = torch.stack(
97
+ [
98
+ xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
99
+ xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
100
+ ],
101
+ -1,
102
+ )
103
+ x_out2 = x_out2.flatten(3)
104
+ return x_out2.type_as(x)
105
+
106
+
107
+ def init_weights(m: nn.Module) -> None:
108
+ if isinstance(m, nn.Conv1d):
109
+ nn.init.trunc_normal_(m.weight, std=0.02)
110
+ nn.init.constant_(m.bias, 0)
111
+
112
+
113
+ # ---------------------------------------------------------------------------
114
+ # Snake1d activation
115
+ # ---------------------------------------------------------------------------
116
+
117
+
118
+ class Snake1d(nn.Module):
119
+ """Snake activation: x + (1/alpha) * sin^2(alpha * x)"""
120
+
121
+ def __init__(self, channels: int) -> None:
122
+ super().__init__()
123
+ self.alpha = nn.Parameter(torch.ones(1, channels, 1))
124
+
125
+ def forward(self, x: Tensor) -> Tensor:
126
+ return x + (1.0 / self.alpha) * torch.sin(self.alpha * x) ** 2
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Causal convolutions (new-style weight_norm via parametrizations)
131
+ # ---------------------------------------------------------------------------
132
+
133
+
134
+ class CausalConvNet(nn.Module):
135
+ def __init__(
136
+ self,
137
+ in_channels: int,
138
+ out_channels: int,
139
+ kernel_size: int,
140
+ dilation: int = 1,
141
+ stride: int = 1,
142
+ groups: int = 1,
143
+ padding: int = None,
144
+ ) -> None:
145
+ super().__init__()
146
+ self.conv = nn.Conv1d(
147
+ in_channels, out_channels, kernel_size,
148
+ stride=stride, dilation=dilation, groups=groups,
149
+ )
150
+ self.stride = stride
151
+ self.kernel_size = (kernel_size - 1) * dilation + 1
152
+ self.dilation = dilation
153
+ self.padding = self.kernel_size - self.stride
154
+
155
+ def forward(self, x: Tensor) -> Tensor:
156
+ pad = self.padding
157
+ extra_padding = get_extra_padding_for_conv1d(
158
+ x, self.kernel_size, self.stride, pad
159
+ )
160
+ x = pad1d(x, (pad, extra_padding), mode="constant", value=0)
161
+ return self.conv(x).contiguous()
162
+
163
+ def weight_norm(self, name: str = "weight", dim: int = 0) -> "CausalConvNet":
164
+ self.conv = new_weight_norm(self.conv, name=name, dim=dim)
165
+ return self
166
+
167
+ def remove_weight_norm(self) -> "CausalConvNet":
168
+ remove_parametrizations(self.conv, "weight")
169
+ return self
170
+
171
+
172
+ class CausalTransConvNet(nn.Module):
173
+ def __init__(
174
+ self,
175
+ in_channels: int,
176
+ out_channels: int,
177
+ kernel_size: int,
178
+ dilation: int = 1,
179
+ stride: int = 1,
180
+ padding: int = None,
181
+ ) -> None:
182
+ super().__init__()
183
+ self.conv = nn.ConvTranspose1d(
184
+ in_channels, out_channels, kernel_size,
185
+ stride=stride, dilation=dilation,
186
+ )
187
+ self.stride = stride
188
+ self.kernel_size = kernel_size
189
+
190
+ def forward(self, x: Tensor) -> Tensor:
191
+ x = self.conv(x)
192
+ pad = self.kernel_size - self.stride
193
+ padding_right = math.ceil(pad)
194
+ padding_left = pad - padding_right
195
+ x = unpad1d(x, (padding_left, padding_right))
196
+ return x.contiguous()
197
+
198
+ def weight_norm(self, name: str = "weight", dim: int = 0) -> "CausalTransConvNet":
199
+ self.conv = new_weight_norm(self.conv, name=name, dim=dim)
200
+ return self
201
+
202
+ def remove_weight_norm(self) -> "CausalTransConvNet":
203
+ remove_parametrizations(self.conv, "weight")
204
+ return self
205
+
206
+
207
+ def CausalWNConv1d(*args, **kwargs) -> CausalConvNet:
208
+ return CausalConvNet(*args, **kwargs).weight_norm()
209
+
210
+
211
+ def CausalWNConvTranspose1d(*args, **kwargs) -> CausalTransConvNet:
212
+ return CausalTransConvNet(*args, **kwargs).weight_norm()
213
+
214
+
215
+ # ---------------------------------------------------------------------------
216
+ # Transformer building blocks
217
+ # ---------------------------------------------------------------------------
218
+
219
+
220
+ class RMSNorm(nn.Module):
221
+ def __init__(self, dim: int, eps: float = 1e-5) -> None:
222
+ super().__init__()
223
+ self.eps = eps
224
+ self.weight = nn.Parameter(torch.ones(dim))
225
+
226
+ def _norm(self, x: Tensor) -> Tensor:
227
+ return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
228
+
229
+ def forward(self, x: Tensor) -> Tensor:
230
+ output = self._norm(x.float()).type_as(x)
231
+ return output * self.weight
232
+
233
+
234
+ class LayerScale(nn.Module):
235
+ def __init__(
236
+ self,
237
+ dim: int,
238
+ init_values: Union[float, Tensor] = 1e-2,
239
+ inplace: bool = False,
240
+ ) -> None:
241
+ super().__init__()
242
+ self.inplace = inplace
243
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
244
+
245
+ def forward(self, x: Tensor) -> Tensor:
246
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
247
+
248
+
249
+ class Attention(nn.Module):
250
+ def __init__(
251
+ self,
252
+ dim: int,
253
+ n_head: int,
254
+ n_local_heads: int,
255
+ head_dim: int,
256
+ attn_dropout_rate: float = 0.1,
257
+ ) -> None:
258
+ super().__init__()
259
+ assert dim % n_head == 0
260
+ total_head_dim = (n_head + 2 * n_local_heads) * head_dim
261
+ self.wqkv = nn.Linear(dim, total_head_dim, bias=False)
262
+ self.wo = nn.Linear(head_dim * n_head, dim, bias=False)
263
+ self.kv_cache = None
264
+ self.n_head = n_head
265
+ self.head_dim = head_dim
266
+ self.n_local_heads = n_local_heads
267
+ self.dim = dim
268
+ self.attn_dropout_rate = attn_dropout_rate
269
+ self.kv_repeat = n_head // n_local_heads
270
+
271
+ def forward(
272
+ self,
273
+ x: Tensor,
274
+ freqs_cis: Tensor,
275
+ mask: Tensor,
276
+ input_pos: Optional[Tensor] = None,
277
+ ) -> Tensor:
278
+ bsz, seqlen, _ = x.shape
279
+ kv_size = self.n_local_heads * self.head_dim
280
+ q, k, v = self.wqkv(x).split([kv_size, kv_size, kv_size], dim=-1)
281
+
282
+ q = q.view(bsz, seqlen, self.n_head, self.head_dim)
283
+ k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
284
+ v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim)
285
+
286
+ q = apply_rotary_emb(q, freqs_cis)
287
+ k = apply_rotary_emb(k, freqs_cis)
288
+
289
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v))
290
+
291
+ if self.kv_repeat > 1:
292
+ k = k.repeat_interleave(self.kv_repeat, dim=1)
293
+ v = v.repeat_interleave(self.kv_repeat, dim=1)
294
+
295
+ y = F.scaled_dot_product_attention(
296
+ q, k, v,
297
+ dropout_p=self.attn_dropout_rate if self.training else 0.0,
298
+ attn_mask=mask,
299
+ )
300
+ y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.head_dim * self.n_head)
301
+ return self.wo(y)
302
+
303
+
304
+ class FeedForward(nn.Module):
305
+ def __init__(self, dim: int, intermediate_size: int, dropout_rate: float = 0.1) -> None:
306
+ super().__init__()
307
+ self.w1 = nn.Linear(dim, intermediate_size, bias=False)
308
+ self.w3 = nn.Linear(dim, intermediate_size, bias=False)
309
+ self.w2 = nn.Linear(intermediate_size, dim, bias=False)
310
+ self.dropout = nn.Dropout(dropout_rate)
311
+
312
+ def forward(self, x: Tensor) -> Tensor:
313
+ return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
314
+
315
+
316
+ class TransformerBlock(nn.Module):
317
+ def __init__(
318
+ self,
319
+ dim: int,
320
+ n_head: int,
321
+ n_local_heads: int,
322
+ head_dim: int,
323
+ intermediate_size: int,
324
+ norm_eps: float = 1e-5,
325
+ dropout_rate: float = 0.1,
326
+ attn_dropout_rate: float = 0.1,
327
+ ) -> None:
328
+ super().__init__()
329
+ self.attention = Attention(dim, n_head, n_local_heads, head_dim, attn_dropout_rate)
330
+ self.feed_forward = FeedForward(dim, intermediate_size, dropout_rate)
331
+ self.ffn_norm = RMSNorm(dim, eps=norm_eps)
332
+ self.attention_norm = RMSNorm(dim, eps=norm_eps)
333
+ self.attention_layer_scale = LayerScale(dim, inplace=True)
334
+ self.ffn_layer_scale = LayerScale(dim, inplace=True)
335
+
336
+ def forward(self, x: Tensor, input_pos: Tensor, freqs_cis: Tensor, mask: Tensor) -> Tensor:
337
+ h = x + self.attention_layer_scale(
338
+ self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
339
+ )
340
+ out = h + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(h)))
341
+ return out
342
+
343
+
344
+ class Transformer(nn.Module):
345
+ def __init__(
346
+ self,
347
+ n_layer: int,
348
+ n_head: int,
349
+ dim: int,
350
+ intermediate_size: int,
351
+ head_dim: int = 64,
352
+ block_size: int = 4096,
353
+ rope_base: float = 10000,
354
+ norm_eps: float = 1e-5,
355
+ dropout_rate: float = 0.1,
356
+ attn_dropout_rate: float = 0.1,
357
+ ) -> None:
358
+ super().__init__()
359
+ self.n_layer = n_layer
360
+ self.n_head = n_head
361
+ self.dim = dim
362
+ self.head_dim = head_dim
363
+ self.block_size = block_size
364
+ n_local_heads = n_head
365
+
366
+ self.layers = nn.ModuleList(
367
+ TransformerBlock(
368
+ dim, n_head, n_local_heads, head_dim,
369
+ intermediate_size, norm_eps, dropout_rate, attn_dropout_rate,
370
+ )
371
+ for _ in range(n_layer)
372
+ )
373
+ self.norm = RMSNorm(dim, eps=norm_eps)
374
+
375
+ freqs_cis = precompute_freqs_cis(block_size, head_dim, rope_base)
376
+ self.register_buffer("freqs_cis", freqs_cis)
377
+
378
+ causal_mask = torch.tril(torch.ones(block_size, block_size, dtype=torch.bool))
379
+ self.register_buffer("causal_mask", causal_mask)
380
+
381
+ def forward(self, x: Tensor, input_pos: Tensor, mask: Optional[Tensor] = None) -> Tensor:
382
+ freqs_cis = self.freqs_cis[input_pos]
383
+ if mask is None:
384
+ mask = self.causal_mask[None, None, input_pos]
385
+ mask = mask[..., input_pos]
386
+ for layer in self.layers:
387
+ x = layer(x, input_pos, freqs_cis, mask)
388
+ x = self.norm(x)
389
+ return x
390
+
391
+
392
+ class WindowLimitedTransformer(Transformer):
393
+ """Transformer with window-limited causal attention."""
394
+
395
+ def __init__(
396
+ self,
397
+ n_layer: int,
398
+ n_head: int,
399
+ dim: int,
400
+ intermediate_size: int,
401
+ head_dim: int = 64,
402
+ block_size: int = 4096,
403
+ rope_base: float = 10000,
404
+ norm_eps: float = 1e-5,
405
+ dropout_rate: float = 0.1,
406
+ attn_dropout_rate: float = 0.1,
407
+ input_dim: int = 1024,
408
+ window_size: Optional[int] = None,
409
+ causal: bool = True,
410
+ channels_first: bool = True,
411
+ ) -> None:
412
+ super().__init__(
413
+ n_layer=n_layer, n_head=n_head, dim=dim,
414
+ intermediate_size=intermediate_size, head_dim=head_dim,
415
+ block_size=block_size, rope_base=rope_base,
416
+ norm_eps=norm_eps, dropout_rate=dropout_rate,
417
+ attn_dropout_rate=attn_dropout_rate,
418
+ )
419
+ self.window_size = window_size
420
+ self.causal = causal
421
+ self.channels_first = channels_first
422
+ # Parent's causal_mask buffer is unused (we compute windowed mask in forward)
423
+ if "causal_mask" in self._buffers:
424
+ del self._buffers["causal_mask"]
425
+ self.look_ahead_conv = nn.Identity()
426
+ self.input_proj = (
427
+ nn.Linear(input_dim, dim) if input_dim != dim else nn.Identity()
428
+ )
429
+ self.output_proj = (
430
+ nn.Linear(dim, input_dim) if input_dim != dim else nn.Identity()
431
+ )
432
+
433
+ def _make_mask(self, max_length: int, device: torch.device = None) -> Tensor:
434
+ if self.causal:
435
+ mask = torch.tril(torch.ones(max_length, max_length, dtype=torch.bool, device=device))
436
+ if self.window_size is not None:
437
+ row_indices = torch.arange(max_length, device=device).view(-1, 1)
438
+ valid_range = (row_indices - self.window_size + 1).clamp(min=0)
439
+ column_indices = torch.arange(max_length, device=device)
440
+ mask = (column_indices >= valid_range) & mask
441
+ else:
442
+ mask = torch.ones(max_length, max_length, dtype=torch.bool, device=device)
443
+ return mask[None, None]
444
+
445
+ def forward(self, x: Tensor, x_lens: Optional[Tensor] = None) -> Tensor:
446
+ if self.channels_first:
447
+ x = x.transpose(1, 2)
448
+ x = self.input_proj(x)
449
+ x = self.look_ahead_conv(x)
450
+ input_pos = torch.arange(x.shape[1], device=x.device)
451
+ mask = self._make_mask(x.shape[1], device=x.device)
452
+ x = super().forward(x, input_pos, mask)
453
+ x = self.output_proj(x)
454
+ if self.channels_first:
455
+ x = x.transpose(1, 2)
456
+ return x
457
+
458
+
459
+ # ---------------------------------------------------------------------------
460
+ # ConvNeXt Block (used in quantizer downsample/upsample)
461
+ # ---------------------------------------------------------------------------
462
+
463
+
464
+ class ConvNeXtBlock(nn.Module):
465
+ def __init__(
466
+ self,
467
+ dim: int,
468
+ layer_scale_init_value: float = 1e-6,
469
+ mlp_ratio: float = 4.0,
470
+ kernel_size: int = 7,
471
+ dilation: int = 1,
472
+ ) -> None:
473
+ super().__init__()
474
+ self.dwconv = CausalConvNet(dim, dim, kernel_size=kernel_size, groups=dim, dilation=dilation)
475
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
476
+ self.pwconv1 = nn.Linear(dim, int(mlp_ratio * dim))
477
+ self.act = nn.GELU()
478
+ self.pwconv2 = nn.Linear(int(mlp_ratio * dim), dim)
479
+ self.gamma = (
480
+ nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
481
+ if layer_scale_init_value > 0
482
+ else None
483
+ )
484
+
485
+ def forward(self, x: Tensor, apply_residual: bool = True) -> Tensor:
486
+ residual = x
487
+ x = self.dwconv(x)
488
+ x = x.permute(0, 2, 1)
489
+ x = self.norm(x)
490
+ x = self.pwconv1(x)
491
+ x = self.act(x)
492
+ x = self.pwconv2(x)
493
+ if self.gamma is not None:
494
+ x = self.gamma * x
495
+ x = x.permute(0, 2, 1)
496
+ if apply_residual:
497
+ x = residual + x
498
+ return x
499
+
500
+
501
+ # ---------------------------------------------------------------------------
502
+ # Encoder / Decoder blocks
503
+ # ---------------------------------------------------------------------------
504
+
505
+
506
+ class ResidualUnit(nn.Module):
507
+ def __init__(self, dim: int = 16, dilation: int = 1, causal: bool = True) -> None:
508
+ super().__init__()
509
+ pad = ((7 - 1) * dilation) // 2
510
+ self.block = nn.Sequential(
511
+ Snake1d(dim),
512
+ CausalWNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
513
+ Snake1d(dim),
514
+ CausalWNConv1d(dim, dim, kernel_size=1),
515
+ )
516
+ self.causal = causal
517
+
518
+ def forward(self, x: Tensor) -> Tensor:
519
+ y = self.block(x)
520
+ pad = x.shape[-1] - y.shape[-1]
521
+ if pad > 0:
522
+ if self.causal:
523
+ x = x[..., :-pad]
524
+ else:
525
+ x = x[..., pad // 2 : -pad // 2]
526
+ return x + y
527
+
528
+
529
+ class EncoderBlock(nn.Module):
530
+ def __init__(
531
+ self,
532
+ dim: int = 16,
533
+ stride: int = 1,
534
+ causal: bool = True,
535
+ n_t_layer: int = 0,
536
+ ) -> None:
537
+ super().__init__()
538
+ transformer_module: nn.Module
539
+ if n_t_layer == 0:
540
+ transformer_module = nn.Identity()
541
+ else:
542
+ transformer_module = WindowLimitedTransformer(
543
+ n_layer=n_t_layer,
544
+ n_head=dim // 64,
545
+ dim=dim,
546
+ intermediate_size=dim * 3,
547
+ head_dim=64,
548
+ block_size=16384,
549
+ dropout_rate=0.1,
550
+ attn_dropout_rate=0.1,
551
+ input_dim=dim,
552
+ window_size=512,
553
+ causal=causal,
554
+ channels_first=True,
555
+ )
556
+ self.block = nn.Sequential(
557
+ ResidualUnit(dim // 2, dilation=1, causal=causal),
558
+ ResidualUnit(dim // 2, dilation=3, causal=causal),
559
+ ResidualUnit(dim // 2, dilation=9, causal=causal),
560
+ Snake1d(dim // 2),
561
+ CausalWNConv1d(
562
+ dim // 2, dim,
563
+ kernel_size=2 * stride,
564
+ stride=stride,
565
+ padding=math.ceil(stride / 2),
566
+ ),
567
+ transformer_module,
568
+ )
569
+
570
+ def forward(self, x: Tensor) -> Tensor:
571
+ return self.block(x)
572
+
573
+
574
+ class Encoder(nn.Module):
575
+ def __init__(
576
+ self,
577
+ d_model: int = 64,
578
+ strides: list = [2, 4, 8, 8],
579
+ d_latent: int = 1024,
580
+ n_transformer_layers: list = [0, 0, 0, 4],
581
+ causal: bool = True,
582
+ ) -> None:
583
+ super().__init__()
584
+ self.block = [CausalWNConv1d(1, d_model, kernel_size=7, padding=3)]
585
+ for stride, n_t_layer in zip(strides, n_transformer_layers):
586
+ d_model *= 2
587
+ self.block.append(
588
+ EncoderBlock(d_model, stride=stride, causal=causal, n_t_layer=n_t_layer)
589
+ )
590
+ self.block.append(Snake1d(d_model))
591
+ self.block.append(CausalWNConv1d(d_model, d_latent, kernel_size=3, padding=1))
592
+ self.block = nn.Sequential(*self.block)
593
+ self.enc_dim = d_model
594
+
595
+ def forward(self, x: Tensor) -> Tensor:
596
+ return self.block(x)
597
+
598
+
599
+ class DecoderBlock(nn.Module):
600
+ def __init__(
601
+ self,
602
+ input_dim: int = 16,
603
+ output_dim: int = 8,
604
+ stride: int = 1,
605
+ causal: bool = True,
606
+ n_t_layer: int = 0,
607
+ ) -> None:
608
+ super().__init__()
609
+ self.block = nn.Sequential(
610
+ Snake1d(input_dim),
611
+ CausalWNConvTranspose1d(
612
+ input_dim, output_dim,
613
+ kernel_size=2 * stride,
614
+ stride=stride,
615
+ padding=math.ceil(stride / 2),
616
+ ),
617
+ ResidualUnit(output_dim, dilation=1, causal=causal),
618
+ ResidualUnit(output_dim, dilation=3, causal=causal),
619
+ ResidualUnit(output_dim, dilation=9, causal=causal),
620
+ )
621
+
622
+ def forward(self, x: Tensor) -> Tensor:
623
+ return self.block(x)
624
+
625
+
626
+ class Decoder(nn.Module):
627
+ def __init__(
628
+ self,
629
+ input_channel: int = 1024,
630
+ channels: int = 1536,
631
+ rates: list = [8, 8, 4, 2],
632
+ d_out: int = 1,
633
+ causal: bool = True,
634
+ n_transformer_layers: list = [0, 0, 0, 0],
635
+ ) -> None:
636
+ super().__init__()
637
+ layers: list[nn.Module] = [CausalWNConv1d(input_channel, channels, kernel_size=7, padding=3)]
638
+ output_dim = channels
639
+ for i, (stride, n_t_layer) in enumerate(zip(rates, n_transformer_layers)):
640
+ input_dim = channels // 2**i
641
+ output_dim = channels // 2 ** (i + 1)
642
+ layers.append(
643
+ DecoderBlock(input_dim, output_dim, stride, causal=causal, n_t_layer=n_t_layer)
644
+ )
645
+ layers.append(Snake1d(output_dim))
646
+ layers.append(CausalWNConv1d(output_dim, d_out, kernel_size=7, padding=3))
647
+ layers.append(nn.Tanh())
648
+ self.model = nn.Sequential(*layers)
649
+
650
+ def forward(self, x: Tensor) -> Tensor:
651
+ return self.model(x)
652
+
653
+
654
+ # ---------------------------------------------------------------------------
655
+ # VQ (Vector Quantize) — uses OLD-style weight_norm for checkpoint compat
656
+ # ---------------------------------------------------------------------------
657
+
658
+
659
+ def _WNConv1d_old(in_channels: int, out_channels: int, kernel_size: int) -> nn.Conv1d:
660
+ """Conv1d with old-style weight_norm (weight_g + weight_v keys)."""
661
+ return old_weight_norm(nn.Conv1d(in_channels, out_channels, kernel_size))
662
+
663
+
664
+ class VectorQuantize(nn.Module):
665
+ def __init__(
666
+ self,
667
+ input_dim: int = 1024,
668
+ codebook_size: int = 1024,
669
+ codebook_dim: int = 8,
670
+ ) -> None:
671
+ super().__init__()
672
+ self.in_proj = _WNConv1d_old(input_dim, codebook_dim, 1)
673
+ self.out_proj = _WNConv1d_old(codebook_dim, input_dim, 1)
674
+ self.codebook = nn.Embedding(codebook_size, codebook_dim)
675
+
676
+ def forward(self, z: Tensor) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
677
+ """
678
+ z: (B, D, T)
679
+ Returns: (z_q, codes, latents, commitment_loss, codebook_loss)
680
+ """
681
+ z_e = self.in_proj(z) # (B, codebook_dim, T)
682
+ z_e_t = z_e.permute(0, 2, 1) # (B, T, codebook_dim)
683
+
684
+ # Nearest neighbor lookup (fp32 for numerical stability under autocast)
685
+ with torch.no_grad():
686
+ z_e_f = z_e_t.float()
687
+ w_f = self.codebook.weight.float()
688
+ d = (
689
+ z_e_f.pow(2).sum(-1, keepdim=True)
690
+ + w_f.pow(2).sum(-1)
691
+ - 2 * z_e_f @ w_f.t()
692
+ )
693
+ indices = d.argmin(-1) # (B, T)
694
+
695
+ z_q_t = self.codebook(indices) # (B, T, codebook_dim)
696
+ z_q = z_q_t.permute(0, 2, 1) # (B, codebook_dim, T)
697
+
698
+ # Straight-through estimator
699
+ commitment_loss = F.mse_loss(z_e, z_q.detach())
700
+ codebook_loss = F.mse_loss(z_q, z_e.detach())
701
+ z_q_st = z_e + (z_q - z_e).detach()
702
+
703
+ z_q_out = self.out_proj(z_q_st) # (B, D, T)
704
+ return z_q_out, indices.unsqueeze(1), z_e, commitment_loss, codebook_loss
705
+
706
+ def from_codes(self, codes: Tensor) -> tp.Tuple[Tensor, Tensor]:
707
+ """
708
+ codes: (B, 1, T)
709
+ Returns: (z_q, z_e)
710
+ """
711
+ indices = codes.squeeze(1) # (B, T)
712
+ z_q_t = self.codebook(indices) # (B, T, codebook_dim)
713
+ z_q = z_q_t.permute(0, 2, 1) # (B, codebook_dim, T)
714
+ z_q_out = self.out_proj(z_q) # (B, D, T)
715
+ return z_q_out, z_q
716
+
717
+
718
+ class ResidualVectorQuantize(nn.Module):
719
+ def __init__(
720
+ self,
721
+ input_dim: int = 1024,
722
+ n_codebooks: int = 9,
723
+ codebook_size: int = 1024,
724
+ codebook_dim: int = 8,
725
+ quantizer_dropout: float = 0.0,
726
+ ) -> None:
727
+ super().__init__()
728
+ self.n_codebooks = n_codebooks
729
+ self._codebook_size = codebook_size
730
+ self.quantizer_dropout = quantizer_dropout
731
+ self.quantizers = nn.ModuleList(
732
+ [VectorQuantize(input_dim, codebook_size, codebook_dim) for _ in range(n_codebooks)]
733
+ )
734
+
735
+ @property
736
+ def codebook_size(self) -> int:
737
+ return self._codebook_size
738
+
739
+ def forward(
740
+ self, z: Tensor, n_quantizers: Optional[int] = None, **kwargs
741
+ ) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
742
+ """
743
+ z: (B, D, T)
744
+ Returns: (z_q, codes, latents, commitment_loss, codebook_loss)
745
+ """
746
+ z_q = torch.zeros_like(z)
747
+ residual = z.clone()
748
+ all_codes = []
749
+ all_latents = []
750
+ commitment_loss = torch.tensor(0.0, device=z.device)
751
+ codebook_loss = torch.tensor(0.0, device=z.device)
752
+
753
+ n_q = n_quantizers if n_quantizers is not None else self.n_codebooks
754
+ if self.training:
755
+ n_dropout = torch.randint(1, n_q + 1, (1,)).item() if self.quantizer_dropout > 0 else n_q
756
+ else:
757
+ n_dropout = n_q
758
+
759
+ for i, quantizer in enumerate(self.quantizers[:n_q]):
760
+ z_q_i, codes_i, latents_i, c_loss, cb_loss = quantizer(residual)
761
+ residual = residual - z_q_i
762
+ if i < n_dropout:
763
+ z_q = z_q + z_q_i
764
+ commitment_loss = commitment_loss + c_loss
765
+ codebook_loss = codebook_loss + cb_loss
766
+ all_codes.append(codes_i)
767
+ all_latents.append(latents_i)
768
+
769
+ codes = torch.cat(all_codes, dim=1) # (B, n_codebooks, T)
770
+ latents = torch.cat(all_latents, dim=1) # (B, n_codebooks*codebook_dim, T)
771
+ return z_q, codes, latents, commitment_loss, codebook_loss
772
+
773
+ def from_codes(self, codes: Tensor) -> tp.Tuple[Tensor, Tensor]:
774
+ """
775
+ codes: (B, n_codebooks, T)
776
+ Returns: (z_q, None)
777
+ """
778
+ z_q = torch.zeros(
779
+ codes.shape[0], self.quantizers[0].out_proj.out_channels, codes.shape[2],
780
+ device=codes.device, dtype=torch.float32,
781
+ )
782
+ for i, quantizer in enumerate(self.quantizers):
783
+ if i >= codes.shape[1]:
784
+ break
785
+ z_q_i, _ = quantizer.from_codes(codes[:, i : i + 1])
786
+ z_q = z_q + z_q_i
787
+ return z_q, None
788
+
789
+
790
+ # ---------------------------------------------------------------------------
791
+ # DownsampleResidualVectorQuantize
792
+ # ---------------------------------------------------------------------------
793
+
794
+
795
+ class DownsampleResidualVectorQuantize(nn.Module):
796
+ def __init__(
797
+ self,
798
+ input_dim: int = 1024,
799
+ n_codebooks: int = 9,
800
+ codebook_dim: int = 8,
801
+ quantizer_dropout: float = 0.5,
802
+ codebook_size: int = 1024,
803
+ semantic_codebook_size: int = 4096,
804
+ downsample_factor: tp.Tuple[int, ...] = (2, 2),
805
+ downsample_dims: tp.Optional[tp.Tuple[int, ...]] = None,
806
+ pre_module: Optional[nn.Module] = None,
807
+ post_module: Optional[nn.Module] = None,
808
+ ) -> None:
809
+ super().__init__()
810
+
811
+ if downsample_dims is None:
812
+ downsample_dims = [input_dim for _ in range(len(downsample_factor))]
813
+
814
+ all_dims = (input_dim,) + tuple(downsample_dims)
815
+
816
+ self.semantic_quantizer = ResidualVectorQuantize(
817
+ input_dim=input_dim, n_codebooks=1,
818
+ codebook_size=semantic_codebook_size, codebook_dim=codebook_dim,
819
+ quantizer_dropout=0.0,
820
+ )
821
+ self.quantizer = ResidualVectorQuantize(
822
+ input_dim=input_dim, n_codebooks=n_codebooks,
823
+ codebook_size=codebook_size, codebook_dim=codebook_dim,
824
+ quantizer_dropout=quantizer_dropout,
825
+ )
826
+
827
+ self.downsample_factor = downsample_factor
828
+ self.downsample_dims = downsample_dims
829
+
830
+ self.downsample = nn.Sequential(
831
+ *[
832
+ nn.Sequential(
833
+ CausalConvNet(all_dims[idx], all_dims[idx + 1], kernel_size=factor, stride=factor),
834
+ ConvNeXtBlock(dim=all_dims[idx + 1]),
835
+ )
836
+ for idx, factor in enumerate(downsample_factor)
837
+ ]
838
+ )
839
+
840
+ self.upsample = nn.Sequential(
841
+ *[
842
+ nn.Sequential(
843
+ CausalTransConvNet(all_dims[idx + 1], all_dims[idx], kernel_size=factor, stride=factor),
844
+ ConvNeXtBlock(dim=all_dims[idx]),
845
+ )
846
+ for idx, factor in reversed(list(enumerate(downsample_factor)))
847
+ ]
848
+ )
849
+
850
+ self.pre_module = pre_module if pre_module is not None else nn.Identity()
851
+ self.post_module = post_module if post_module is not None else nn.Identity()
852
+
853
+ self._init_ds_us_weights()
854
+
855
+ def _init_ds_us_weights(self) -> None:
856
+ for m in list(self.downsample.modules()) + list(self.upsample.modules()):
857
+ if isinstance(m, (nn.Conv1d, nn.Linear)):
858
+ nn.init.trunc_normal_(m.weight, std=0.02)
859
+ if m.bias is not None:
860
+ nn.init.constant_(m.bias, 0)
861
+
862
+ def forward(
863
+ self, z: Tensor, n_quantizers: Optional[int] = None, **kwargs
864
+ ) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
865
+ original_shape = z.shape
866
+ z = self.downsample(z)
867
+ z = self.pre_module(z)
868
+
869
+ semantic_z, semantic_codes, semantic_latents, sc_loss, scb_loss = self.semantic_quantizer(z)
870
+ residual_z = z - semantic_z
871
+ residual_z, codes, latents, c_loss, cb_loss = self.quantizer(residual_z, n_quantizers=n_quantizers)
872
+ z = semantic_z + residual_z
873
+
874
+ commitment_loss = c_loss + sc_loss
875
+ codebook_loss = cb_loss + scb_loss
876
+ codes = torch.cat([semantic_codes, codes], dim=1)
877
+ latents = torch.cat([semantic_latents, latents], dim=1)
878
+
879
+ z = self.post_module(z)
880
+ z = self.upsample(z)
881
+
882
+ diff = original_shape[-1] - z.shape[-1]
883
+ if diff > 0:
884
+ z = F.pad(z, (abs(diff), 0))
885
+ elif diff < 0:
886
+ z = z[..., abs(diff):]
887
+
888
+ return z, codes, latents, commitment_loss, codebook_loss
889
+
890
+ def encode_only(
891
+ self, z: Tensor, n_quantizers: tp.Optional[int] = None
892
+ ) -> Tensor:
893
+ """Encode to codes only, skipping post_module and upsample."""
894
+ z = self.downsample(z)
895
+ z = self.pre_module(z)
896
+
897
+ semantic_z, semantic_codes, _, _, _ = self.semantic_quantizer(z)
898
+ residual_z = z - semantic_z
899
+ _, codes, _, _, _ = self.quantizer(residual_z, n_quantizers=n_quantizers)
900
+
901
+ return torch.cat([semantic_codes, codes], dim=1)
902
+
903
+ def decode(self, indices: Tensor) -> Tensor:
904
+ new_indices = torch.zeros_like(indices)
905
+ new_indices[:, 0] = torch.clamp(indices[:, 0], max=self.semantic_quantizer.codebook_size - 1)
906
+ new_indices[:, 1:] = torch.clamp(indices[:, 1:], max=self.quantizer.codebook_size - 1)
907
+
908
+ z_q_semantic, _ = self.semantic_quantizer.from_codes(new_indices[:, :1])
909
+ z_q_residual, _ = self.quantizer.from_codes(new_indices[:, 1:])
910
+ z_q = z_q_semantic + z_q_residual
911
+ z_q = self.post_module(z_q)
912
+ z_q = self.upsample(z_q)
913
+ return z_q
914
+
915
+
916
+ # ---------------------------------------------------------------------------
917
+ # ECodec — top-level model
918
+ # ---------------------------------------------------------------------------
919
+
920
+
921
+ class ECodec(nn.Module):
922
+ """
923
+ ECodec audio codec.
924
+
925
+ Sample rate: 44100 Hz
926
+ Hop length: 512 (encoder strides: 2*4*8*8 = 512)
927
+ Latent dim: 1024
928
+ Codebooks: 1 semantic (4096 entries) + 9 residual (1024 entries each) = 10 total
929
+ Quantizer downsamples by 4x (factors [2,2]), so code rate = 44100 / 512 / 4 ~ 21.5 Hz
930
+ """
931
+
932
+ def __init__(self) -> None:
933
+ super().__init__()
934
+
935
+ # ---- Hardcoded config ----
936
+ encoder_dim = 64
937
+ encoder_rates = [2, 4, 8, 8]
938
+ encoder_transformer_layers = [0, 0, 0, 4]
939
+ latent_dim = 1024
940
+ decoder_dim = 1536
941
+ decoder_rates = [8, 8, 4, 2]
942
+ decoder_transformer_layers = [0, 0, 0, 0]
943
+ sample_rate = 44100
944
+
945
+ n_codebooks = 9
946
+ codebook_size = 1024
947
+ codebook_dim = 8
948
+ semantic_codebook_size = 4096
949
+ downsample_factor = (2, 2)
950
+
951
+ self.sample_rate = sample_rate
952
+ self.hop_length = 1
953
+ for r in encoder_rates:
954
+ self.hop_length *= r # = 512
955
+ self.latent_dim = latent_dim
956
+ self.frame_length = self.hop_length * 4 # = 2048
957
+
958
+ # ---- Encoder ----
959
+ self.encoder = Encoder(
960
+ d_model=encoder_dim,
961
+ strides=encoder_rates,
962
+ d_latent=latent_dim,
963
+ n_transformer_layers=encoder_transformer_layers,
964
+ causal=True,
965
+ )
966
+
967
+ # ---- Quantizer ----
968
+ # Pre/post modules are WindowLimitedTransformers with window_size=128
969
+ q_pre = WindowLimitedTransformer(
970
+ n_layer=8, n_head=16, dim=1024, intermediate_size=3072,
971
+ head_dim=64, block_size=4096,
972
+ dropout_rate=0.1, attn_dropout_rate=0.1,
973
+ input_dim=1024, window_size=128, causal=True, channels_first=True,
974
+ )
975
+ q_post = WindowLimitedTransformer(
976
+ n_layer=8, n_head=16, dim=1024, intermediate_size=3072,
977
+ head_dim=64, block_size=4096,
978
+ dropout_rate=0.1, attn_dropout_rate=0.1,
979
+ input_dim=1024, window_size=128, causal=True, channels_first=True,
980
+ )
981
+ self.quantizer = DownsampleResidualVectorQuantize(
982
+ input_dim=latent_dim,
983
+ n_codebooks=n_codebooks,
984
+ codebook_dim=codebook_dim,
985
+ quantizer_dropout=0.5,
986
+ codebook_size=codebook_size,
987
+ semantic_codebook_size=semantic_codebook_size,
988
+ downsample_factor=downsample_factor,
989
+ pre_module=q_pre,
990
+ post_module=q_post,
991
+ )
992
+
993
+ # ---- Decoder ----
994
+ self.decoder = Decoder(
995
+ input_channel=latent_dim,
996
+ channels=decoder_dim,
997
+ rates=decoder_rates,
998
+ d_out=1,
999
+ causal=True,
1000
+ n_transformer_layers=decoder_transformer_layers,
1001
+ )
1002
+
1003
+ self.apply(init_weights)
1004
+ self._autocast_dtype: tp.Optional[torch.dtype] = None
1005
+
1006
+ # ---- Public API ----
1007
+
1008
+ @staticmethod
1009
+ def load(checkpoint_path: str, device: str = "cpu") -> "ECodec":
1010
+ """Load ECodec from a checkpoint file."""
1011
+ model = ECodec()
1012
+ state_dict = torch.load(checkpoint_path, map_location=device, weights_only=True)
1013
+ # Drop causal_mask buffers from checkpoint (freed in WindowLimitedTransformer, saves ~288MB)
1014
+ state_dict = {k: v for k, v in state_dict.items() if not k.endswith("causal_mask")}
1015
+ model.load_state_dict(state_dict, strict=True)
1016
+ model.to(device)
1017
+ model.eval()
1018
+ return model
1019
+
1020
+ def _remove_weight_norms(self) -> None:
1021
+ """Remove all weight norms for faster inference (no recomputation)."""
1022
+ for module in self.modules():
1023
+ if isinstance(module, (CausalConvNet, CausalTransConvNet)):
1024
+ try:
1025
+ module.remove_weight_norm()
1026
+ except (ValueError, RuntimeError):
1027
+ pass
1028
+ # Old-style weight_norm on VQ conv layers (weight_g / weight_v)
1029
+ for module in self.modules():
1030
+ if isinstance(module, nn.Conv1d) and hasattr(module, "weight_g"):
1031
+ torch.nn.utils.remove_weight_norm(module)
1032
+
1033
+ def _encode_impl(self, audio: Tensor) -> tp.Tuple[Tensor, Tensor]:
1034
+ """Encode pipeline as single graph for torch.compile."""
1035
+ z = self.encoder(audio)
1036
+ codes = self.quantizer.encode_only(z)
1037
+ return codes, z
1038
+
1039
+ def _decode_impl(self, codes: Tensor) -> Tensor:
1040
+ """Decode pipeline as single graph for torch.compile."""
1041
+ z = self.quantizer.decode(codes)
1042
+ return self.decoder(z)
1043
+
1044
+ def optimize(
1045
+ self,
1046
+ dtype: torch.dtype = torch.float32,
1047
+ compile: bool = True,
1048
+ **compile_kwargs,
1049
+ ) -> "ECodec":
1050
+ """
1051
+ Optimize for faster GPU inference with torch.compile and optional autocast.
1052
+
1053
+ Parameters
1054
+ ----------
1055
+ dtype : torch.dtype
1056
+ torch.float32 (default) for exact codes, or torch.bfloat16 for
1057
+ ~2x extra speedup with approximate codes (~60% codebook mismatch
1058
+ vs fp32 due to VQ sensitivity to small numerical differences).
1059
+ fp16 is NOT supported.
1060
+ compile : bool
1061
+ Apply torch.compile to encoder, decoder, and quantizer.
1062
+ **compile_kwargs
1063
+ Extra kwargs for torch.compile (e.g. mode="reduce-overhead").
1064
+ """
1065
+ if dtype == torch.float16:
1066
+ raise ValueError(
1067
+ "fp16 causes numerical instability in Snake activations and "
1068
+ "VQ distance computation. Use torch.bfloat16 instead."
1069
+ )
1070
+ self._autocast_dtype = dtype if dtype != torch.float32 else None
1071
+ self._remove_weight_norms()
1072
+ if compile:
1073
+ self._encode_impl = torch.compile(self._encode_impl, **compile_kwargs)
1074
+ self._decode_impl = torch.compile(self._decode_impl, **compile_kwargs)
1075
+ return self
1076
+
1077
+ def _autocast_ctx(self, ref: Tensor):
1078
+ """Return autocast context if enabled and on CUDA, else nullcontext."""
1079
+ if self._autocast_dtype is not None and ref.is_cuda:
1080
+ return torch.autocast("cuda", dtype=self._autocast_dtype)
1081
+ return nullcontext()
1082
+
1083
+ def _pad_audio(self, audio: Tensor) -> Tensor:
1084
+ """Pad audio to multiple of frame_length."""
1085
+ length = audio.shape[-1]
1086
+ right_pad = math.ceil(length / self.frame_length) * self.frame_length - length
1087
+ if right_pad > 0:
1088
+ audio = F.pad(audio, (0, right_pad))
1089
+ return audio
1090
+
1091
+ @torch.inference_mode()
1092
+ def encode(self, audio: Tensor) -> tp.Tuple[Tensor, Tensor]:
1093
+ """
1094
+ Encode audio waveform to discrete codes and continuous latent.
1095
+
1096
+ Parameters
1097
+ ----------
1098
+ audio : Tensor of shape (B, 1, T)
1099
+ Raw waveform at 44100 Hz.
1100
+
1101
+ Returns
1102
+ -------
1103
+ codes : Tensor of shape (B, 10, T')
1104
+ Discrete codebook indices. First row is semantic, rest are residual.
1105
+ continuous_z : Tensor of shape (B, 1024, T/512)
1106
+ Pre-quantization continuous latent from encoder.
1107
+ """
1108
+ audio = self._pad_audio(audio)
1109
+ with self._autocast_ctx(audio):
1110
+ return self._encode_impl(audio)
1111
+
1112
+ @torch.inference_mode()
1113
+ def decode(self, codes: Tensor) -> Tensor:
1114
+ """
1115
+ Decode discrete codes back to audio.
1116
+
1117
+ Parameters
1118
+ ----------
1119
+ codes : Tensor of shape (B, 10, T')
1120
+ Discrete codebook indices.
1121
+
1122
+ Returns
1123
+ -------
1124
+ audio : Tensor of shape (B, 1, T)
1125
+ Reconstructed waveform.
1126
+ """
1127
+ if codes.ndim == 2:
1128
+ codes = codes.unsqueeze(0)
1129
+ with self._autocast_ctx(codes):
1130
+ return self._decode_impl(codes)
1131
+
1132
+ @torch.inference_mode()
1133
+ def encode_continuous(self, audio: Tensor) -> Tensor:
1134
+ """
1135
+ Encode audio to continuous latent (after downsample + pre_module, before VQ).
1136
+
1137
+ Parameters
1138
+ ----------
1139
+ audio : Tensor of shape (B, 1, T)
1140
+
1141
+ Returns
1142
+ -------
1143
+ z : Tensor of shape (B, 1024, T/2048)
1144
+ Continuous latent at ~21.5 Hz (encoder 86Hz / quantizer downsample 4x).
1145
+ """
1146
+ audio = self._pad_audio(audio)
1147
+ with self._autocast_ctx(audio):
1148
+ z = self.encoder(audio) # (B, 1024, T/512) at 86Hz
1149
+ z = self.quantizer.downsample(z) # (B, 1024, T/2048) at ~21.5Hz
1150
+ z = self.quantizer.pre_module(z) # transformer
1151
+ return z
1152
+
1153
+ @torch.inference_mode()
1154
+ def decode_continuous(self, z: Tensor) -> Tensor:
1155
+ """
1156
+ Decode from continuous latent (after pre_module, before VQ), bypassing VQ.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ z : Tensor of shape (B, 1024, T')
1161
+ Latent from encode_continuous.
1162
+
1163
+ Returns
1164
+ -------
1165
+ audio : Tensor of shape (B, 1, T)
1166
+ """
1167
+ with self._autocast_ctx(z):
1168
+ z = self.quantizer.post_module(z) # transformer
1169
+ z = self.quantizer.upsample(z) # back to 86Hz
1170
+ return self.decoder(z)
1171
+
1172
+
1173
+ # ---------------------------------------------------------------------------
1174
+ # CLI test
1175
+ # ---------------------------------------------------------------------------
1176
+
1177
+ if __name__ == "__main__":
1178
+ import os
1179
+ import sys
1180
+
1181
+ ckpt_path = os.path.join(os.path.dirname(__file__), "codec.pth")
1182
+ if not os.path.exists(ckpt_path):
1183
+ print(f"Checkpoint not found at {ckpt_path}")
1184
+ sys.exit(1)
1185
+
1186
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1187
+ print(f"Loading ECodec on {device}...")
1188
+ codec = ECodec.load(ckpt_path, device=device)
1189
+ print(f"Loaded. Parameters: {sum(p.numel() for p in codec.parameters()):,}")
1190
+
1191
+ if device == "cuda":
1192
+ codec.optimize()
1193
+ print("Optimized with bf16 + torch.compile")
1194
+
1195
+ # Test encode/decode roundtrip
1196
+ x = torch.randn(1, 1, 44100, device=device)
1197
+ print(f"Input: {x.shape}")
1198
+
1199
+ codes, z_cont = codec.encode(x)
1200
+ print(f"Codes: {codes.shape}, Continuous z: {z_cont.shape}")
1201
+
1202
+ audio_out = codec.decode(codes)
1203
+ print(f"Decoded audio: {audio_out.shape}")
1204
+
1205
+ z = codec.encode_continuous(x)
1206
+ print(f"Continuous encode: {z.shape}")
1207
+
1208
+ audio_direct = codec.decode_continuous(z)
1209
+ print(f"Continuous decode: {audio_direct.shape}")
1210
+
1211
+ print("All tests passed.")
ecodec_fast/istft_head.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ISTFTHead vendored from vocos 0.1.0 (MIT, https://github.com/gemelo-ai/vocos) to avoid the
2
+ vocos -> encodec dependency chain. Unchanged except for imports."""
3
+ import torch
4
+ from torch import nn
5
+
6
+
7
+ class ISTFT(nn.Module):
8
+ """iSTFT with "same" padding (torch.istft only supports center=True with windowing)."""
9
+
10
+ def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"):
11
+ super().__init__()
12
+ if padding not in ["center", "same"]:
13
+ raise ValueError("Padding must be 'center' or 'same'.")
14
+ self.padding = padding
15
+ self.n_fft = n_fft
16
+ self.hop_length = hop_length
17
+ self.win_length = win_length
18
+ self.register_buffer("window", torch.hann_window(win_length))
19
+
20
+ def forward(self, spec: torch.Tensor) -> torch.Tensor:
21
+ if self.padding == "center":
22
+ return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True)
23
+ pad = (self.win_length - self.hop_length) // 2
24
+ assert spec.dim() == 3, "Expected a 3D tensor as input"
25
+ B, N, T = spec.shape
26
+ ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward")
27
+ ifft = ifft * self.window[None, :, None]
28
+ output_size = (T - 1) * self.hop_length + self.win_length
29
+ y = torch.nn.functional.fold(
30
+ ifft, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length),
31
+ )[:, 0, 0, pad:-pad]
32
+ window_sq = self.window.square().expand(1, T, -1).transpose(1, 2)
33
+ window_envelope = torch.nn.functional.fold(
34
+ window_sq, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length),
35
+ ).squeeze()[pad:-pad]
36
+ assert (window_envelope > 1e-11).all()
37
+ return y / window_envelope
38
+
39
+
40
+ class ISTFTHead(nn.Module):
41
+ """Predicts STFT magnitude/phase from features [B, L, H] and returns audio [B, T]."""
42
+
43
+ def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"):
44
+ super().__init__()
45
+ self.out = torch.nn.Linear(dim, n_fft + 2)
46
+ self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
47
+
48
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
49
+ x = self.out(x).transpose(1, 2)
50
+ mag, p = x.chunk(2, dim=1)
51
+ mag = torch.clip(torch.exp(mag), max=1e2)
52
+ S = mag * (torch.cos(p) + 1j * torch.sin(p))
53
+ return self.istft(S)
ecodec_fast/model_nsf_v2.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NSFNanoDecoder V2: NSF source driven by a CREPE-style BINNED F0 classifier
2
+ (F0BinnedPredictor) instead of MSE-regression -> no octave-averaging mush, free UV gate.
3
+ Backbone (proj/blocks/norm/head/source_proj/m_source) IDENTICAL to NSFNanoDecoder ->
4
+ warm-start from a v1 nsf checkpoint (the binned f0-head reinits; f0 conv-trunk transfers)."""
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from nano_core import CausalConvNeXt, Z86_DIM
9
+ from istft_head import ISTFTHead
10
+ from nsf_source import SourceModuleHnNSF, F0BinnedPredictor
11
+
12
+
13
+ class NSFNanoDecoderV2(nn.Module):
14
+ def __init__(self, in_dim: int = Z86_DIM, dim: int = 768, n_blocks: int = 12,
15
+ n_fft: int = 1116, hop: int = 279, sr: int = 24000, harmonic_num: int = 8,
16
+ n_bins: int = 256, fmin: float = 50.0, fmax: float = 800.0, ref_cond: bool = False):
17
+ super().__init__()
18
+ self.proj = nn.Conv1d(in_dim, dim, 1)
19
+ self.blocks = nn.ModuleList([CausalConvNeXt(dim) for _ in range(n_blocks)])
20
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
21
+ self.head = ISTFTHead(dim=dim, n_fft=n_fft, hop_length=hop, padding="same")
22
+ self.f0_predictor = F0BinnedPredictor(in_ch=in_dim, hid=256, n_bins=n_bins,
23
+ fmin=fmin, fmax=fmax, ref_cond=ref_cond)
24
+ self.m_source = SourceModuleHnNSF(sr, harmonic_num=harmonic_num)
25
+ self.source_proj = nn.Conv1d(n_fft + 2, dim, 1)
26
+ self.hop, self.n_fft, self.sr = hop, n_fft, sr
27
+ self.register_buffer("src_win", torch.hann_window(n_fft), persistent=False)
28
+
29
+ def _excitation_spec(self, z86, ref=None, ref_stats=None, prior_strength=0.0):
30
+ logits = self.f0_predictor(z86, ref) # [B, n_bins, T]
31
+ f0 = self.f0_predictor.decode(logits, ref_stats=ref_stats,
32
+ prior_strength=prior_strength) # [B, T] Hz (0=unvoiced)
33
+ f0_up = F.interpolate(f0[:, None], scale_factor=self.hop, mode="nearest")[:, 0]
34
+ src, _, _ = self.m_source(f0_up[..., None])
35
+ with torch.autocast(z86.device.type, enabled=False):
36
+ s = torch.stft(src.squeeze(-1).float(), self.n_fft, self.hop, self.n_fft,
37
+ self.src_win.float(), center=True, return_complex=True)
38
+ return torch.cat([s.real, s.imag], dim=1), logits, f0
39
+
40
+ def forward(self, z86, return_f0: bool = False, ref=None,
41
+ ref_stats=None, prior_strength: float = 0.0):
42
+ """ref_stats=(log-F0 mean, std) of a speaker prompt + prior_strength>0 anchors the
43
+ predicted pitch to that speaker's range (see F0BinnedPredictor.ref_stats_from_wav)."""
44
+ x = self.proj(z86)
45
+ s_feat, logits, f0 = self._excitation_spec(z86, ref, ref_stats, prior_strength)
46
+ Tm = min(s_feat.shape[-1], x.shape[-1])
47
+ x = x[..., :Tm] + self.source_proj(s_feat[..., :Tm])
48
+ for b in self.blocks:
49
+ x = b(x)
50
+ x = self.norm(x.transpose(1, 2))
51
+ audio = self.head(x)
52
+ return (audio, logits[..., :Tm], f0[..., :Tm]) if return_f0 else audio
53
+
54
+ def load_backbone(self, state):
55
+ """Warm-start matching-shape tensors from a v1 NSFNanoDecoder (or v2) state_dict.
56
+ f0_predictor conv-trunk transfers (same shape); the binned head (out) reinits."""
57
+ own = self.state_dict()
58
+ loaded = {k: v for k, v in state.items() if k in own and own[k].shape == v.shape}
59
+ own.update(loaded)
60
+ self.load_state_dict(own)
61
+ return len(loaded), len(state)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ torch.set_grad_enabled(False)
66
+ g = NSFNanoDecoderV2(dim=768, n_blocks=12).eval()
67
+ n = sum(p.numel() for p in g.parameters())
68
+ z = torch.randn(2, 1024, 40)
69
+ a, logits, f0 = g(z, return_f0=True)
70
+ print(f"NSFNanoDecoderV2 {n/1e6:.2f}M | z {tuple(z.shape)} -> audio {tuple(a.shape)} "
71
+ f"logits {tuple(logits.shape)} f0 {tuple(f0.shape)}")
72
+ print(f"audio finite: {torch.isfinite(a).all().item()} | f0 range [{f0.min():.0f},{f0.max():.0f}]Hz "
73
+ f"| unvoiced frames: {(f0[0]==0).sum().item()}/{f0.shape[-1]}")
ecodec_fast/nano_core.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core pieces of the ECodec-nano decoder (extracted from the training tree for deployment).
2
+
3
+ Front-end (frozen, reused from ECodec): codes[:N] -> z86 latent [B,1024,T] @86.13Hz
4
+ via the trained, checkerboard-safe (k=stride) DownsampleRVQ.decode (from_codes + upsample).
5
+ Backbone: causal ConvNeXt on the frame rate; synthesis is a fixed iSTFT (no conv-to-waveform).
6
+
7
+ Rates: ECodec code rate 21.53Hz -> upsample x4 -> z86 86.13Hz -> iSTFT hop 279 -> ~24k.
8
+ """
9
+ import sys
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ import os
15
+
16
+ _HERE = os.path.dirname(os.path.abspath(__file__))
17
+ ECODEC_ROOT = _HERE # ECodec class defs live next to this file
18
+ _MODELS = os.environ.get("ECODEC_WEIGHTS") or os.path.join(_HERE, "..") # repo root by default
19
+ # With the distilled post_module the quantizer bundle no longer needs the 417 MB
20
+ # teacher, so the slim file (81 MB) is preferred when present.
21
+ ECODEC_CKPT = os.environ.get("ESP_QUANTIZER") or next(
22
+ (p for p in (os.path.join(_MODELS, "ecodec_quantizer_slim.pt"),
23
+ os.path.join(_MODELS, "ecodec_quantizer.pt")) if os.path.exists(p)),
24
+ os.path.join(_MODELS, "ecodec_quantizer.pt"))
25
+ Z86_DIM = 1024
26
+
27
+
28
+ class CausalConvNeXt(nn.Module):
29
+ """Causal ConvNeXt block: left-padded depthwise conv + pointwise MLP."""
30
+ def __init__(self, dim: int, kernel: int = 7, mult: int = 3):
31
+ super().__init__()
32
+ self.pad = kernel - 1
33
+ self.dw = nn.Conv1d(dim, dim, kernel, groups=dim)
34
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
35
+ self.pw1 = nn.Linear(dim, dim * mult)
36
+ self.act = nn.GELU()
37
+ self.pw2 = nn.Linear(dim * mult, dim)
38
+ self.gamma = nn.Parameter(1e-6 * torch.ones(dim))
39
+
40
+ def forward(self, x): # x [B,C,T]
41
+ r = x
42
+ x = self.dw(F.pad(x, (self.pad, 0))) # causal: left-pad only
43
+ x = x.transpose(1, 2)
44
+ x = self.pw2(self.act(self.pw1(self.norm(x))))
45
+ x = (self.gamma * x).transpose(1, 2)
46
+ return r + x
47
+
48
+
49
+ class _PostVQStudent(nn.Module):
50
+ """Distilled post_module: matches the teacher's `z_q -> z_q` interface.
51
+
52
+ The student is conditioned on the codebook count, so it is told how many
53
+ codebooks the request actually used.
54
+ """
55
+ def __init__(self, net, nq: int = 9):
56
+ super().__init__()
57
+ self.net = net
58
+ self.nq = nq
59
+
60
+ def forward(self, z_q):
61
+ return self.net(z_q, nq=self.nq)[0]
62
+
63
+
64
+ def _default_student():
65
+ p = os.path.join(_MODELS, "postvq_student_90k.pt")
66
+ return p if os.path.exists(p) else None
67
+
68
+
69
+ def _load_postvq_student(ckpt: str):
70
+ sys.path.insert(0, _HERE) if _HERE not in sys.path else None
71
+ from postvq_student import StudentTransformer # noqa: E402
72
+ ck = torch.load(ckpt, map_location="cpu", weights_only=False, mmap=True)
73
+ cfg = ck.get("cfg") or {}
74
+ net = StudentTransformer(**cfg) if isinstance(cfg, dict) else StudentTransformer()
75
+ try:
76
+ net.load_state_dict(ck["student"], assign=True)
77
+ except TypeError:
78
+ net.load_state_dict(ck["student"])
79
+ net.eval()
80
+ return _PostVQStudent(net)
81
+
82
+
83
+ class ECodecFrontend(nn.Module):
84
+ """Frozen: codes[:N] -> z86 [B,1024,T86]. Reuses ECodec's trained from_codes+upsample.
85
+
86
+ Production: loads the slim decode-side quantizer weights (post_module + upsample
87
+ + codebooks, ~500 MB) instead of the full 1.9 GB ECodec checkpoint. The tensors
88
+ are the ones the v2 decoder was trained against, so output is bit-identical.
89
+ """
90
+ def __init__(self, ckpt: str = ECODEC_CKPT, ecodec_root: str = ECODEC_ROOT,
91
+ dtype: torch.dtype | None = None):
92
+ super().__init__()
93
+ if ecodec_root not in sys.path:
94
+ sys.path.insert(0, ecodec_root)
95
+ from ecodec import DownsampleResidualVectorQuantize, WindowLimitedTransformer
96
+
97
+ # Decode is `from_codes -> post_module -> upsample`; the encode-side
98
+ # pre_module (417 MB) and downsample (80 MB) are never touched, and
99
+ # building the surrounding ECodec would also allocate the encoder and
100
+ # the 54M conv decoder. Construct just the quantizer and stub out the
101
+ # encode half, so nothing unused is ever allocated.
102
+ #
103
+ # post_module is the 109M teacher transformer (417 MB). ESP_POSTVQ=student
104
+ # swaps in the distilled 14.7M student (56 MB) — validated as perceptually
105
+ # equivalent; see FINDINGS §3 in the ECodec-nano tree.
106
+ student_ckpt = os.environ.get("ESP_POSTVQ_CKPT") or _default_student()
107
+ self.postvq = "teacher"
108
+ self._teacher_preloaded = False
109
+ if os.environ.get("ESP_POSTVQ", "student") == "student" and student_ckpt:
110
+ q_post = _load_postvq_student(student_ckpt)
111
+ self.postvq = "student"
112
+ else:
113
+ q_post = WindowLimitedTransformer(
114
+ n_layer=8, n_head=16, dim=1024, intermediate_size=3072,
115
+ head_dim=64, block_size=4096, dropout_rate=0.1, attn_dropout_rate=0.1,
116
+ input_dim=1024, window_size=128, causal=True, channels_first=True)
117
+ tw = os.environ.get("ESP_POSTVQ_TEACHER") or os.path.join(
118
+ _MODELS, "postvq_teacher.pt")
119
+ if os.path.exists(tw): # standalone teacher weights
120
+ tsd = torch.load(tw, map_location="cpu", weights_only=False, mmap=True)
121
+ try:
122
+ q_post.load_state_dict(tsd, assign=True)
123
+ except TypeError:
124
+ q_post.load_state_dict(tsd)
125
+ self._teacher_preloaded = True
126
+ q = DownsampleResidualVectorQuantize(
127
+ input_dim=1024, n_codebooks=9, codebook_dim=8, quantizer_dropout=0.5,
128
+ codebook_size=1024, semantic_codebook_size=4096,
129
+ downsample_factor=(2, 2), pre_module=None, post_module=q_post)
130
+ q.pre_module = nn.Identity()
131
+ q.downsample = nn.Identity()
132
+
133
+ # mmap + assign: the weights stay file-backed instead of being copied into
134
+ # anonymous memory, so the kernel can evict them under pressure and several
135
+ # worker processes share one copy.
136
+ drop = ["pre_module.", "downsample."]
137
+ if self.postvq == "student" or self._teacher_preloaded:
138
+ drop.append("post_module.") # already carries its own weights
139
+ sd = torch.load(ckpt, map_location="cpu", weights_only=False, mmap=True)
140
+ sd = {k: v for k, v in sd.items() if not k.startswith(tuple(drop))}
141
+ try:
142
+ missing, unexpected = q.load_state_dict(sd, strict=False, assign=True)
143
+ except TypeError: # torch < 2.1: no assign=
144
+ missing, unexpected = q.load_state_dict(sd, strict=False)
145
+ # `in_proj` lives on the encode side (decode goes through out_proj), so
146
+ # its absence from the slim bundle is expected.
147
+ needed = ["upsample.", "quantizer.", "semantic_quantizer."]
148
+ if self.postvq == "teacher" and not self._teacher_preloaded:
149
+ needed.append("post_module.")
150
+ blocking = [k for k in missing
151
+ if "in_proj" not in k and k.startswith(tuple(needed))]
152
+ if blocking:
153
+ raise RuntimeError(f"quantizer weights missing: {blocking[:4]} "
154
+ f"(+{len(blocking) - 4} more)")
155
+ self.quantizer = q
156
+ if dtype is not None:
157
+ self.quantizer.to(dtype)
158
+ for p in self.parameters():
159
+ p.requires_grad_(False)
160
+ self.eval()
161
+
162
+ @torch.no_grad()
163
+ def forward(self, codes): # codes [B,N,T] long (N<=10)
164
+ return self.quantizer.decode(codes) # z86 [B,1024, T*4]
ecodec_fast/nsf_source.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NSF harmonic source — lifted from CosyVoice3 HiFTNet (cosyvoice/hifigan/generator.py),
2
+ self-contained. F0 -> sine harmonics -> merged excitation. Plus a light causal F0 predictor
3
+ (z86 -> F0 @86Hz) so we can supervise it with GT pitch during training.
4
+
5
+ Robovoice = iSTFT inventing phase from nothing. This gives the iSTFT head a real
6
+ harmonic-phase reference (excitation STFT), the way HiFTNet does.
7
+ """
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.distributions.uniform import Uniform
13
+
14
+
15
+ class SineGen(nn.Module):
16
+ """CosyVoice/HiFTNet SineGen (type 1). f0 [B,L,1] @audio-rate -> sines [B,L,harmonic+1]."""
17
+ def __init__(self, samp_rate, harmonic_num=0, sine_amp=0.1, noise_std=0.003, voiced_threshold=0):
18
+ super().__init__()
19
+ self.sine_amp, self.noise_std = sine_amp, noise_std
20
+ self.harmonic_num, self.sampling_rate, self.voiced_threshold = harmonic_num, samp_rate, voiced_threshold
21
+
22
+ def _f02uv(self, f0):
23
+ return (f0 > self.voiced_threshold).float()
24
+
25
+ @torch.no_grad()
26
+ def forward(self, f0): # f0 [B, L, 1]
27
+ f0 = f0.transpose(1, 2) # [B, 1, L]
28
+ F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1)), device=f0.device)
29
+ for i in range(self.harmonic_num + 1):
30
+ F_mat[:, i:i + 1, :] = f0 * (i + 1) / self.sampling_rate
31
+ theta = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
32
+ phase = Uniform(-np.pi, np.pi).sample((f0.size(0), self.harmonic_num + 1, 1)).to(f0.device)
33
+ phase[:, 0, :] = 0
34
+ sine = self.sine_amp * torch.sin(theta + phase)
35
+ uv = self._f02uv(f0)
36
+ noise = (uv * self.noise_std + (1 - uv) * self.sine_amp / 3) * torch.randn_like(sine)
37
+ sine = sine * uv + noise
38
+ return sine.transpose(1, 2), uv.transpose(1, 2), noise # [B,L,harm+1], [B,L,1], _
39
+
40
+
41
+ class SourceModuleHnNSF(nn.Module):
42
+ """CosyVoice/HiFTNet source module. f0 [B,L,1] -> merged excitation [B,L,1]."""
43
+ def __init__(self, sampling_rate, harmonic_num=8, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0):
44
+ super().__init__()
45
+ self.sine_amp, self.noise_std = sine_amp, add_noise_std
46
+ self.l_sin_gen = SineGen(sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod)
47
+ self.l_linear = nn.Linear(harmonic_num + 1, 1)
48
+ self.l_tanh = nn.Tanh()
49
+
50
+ def forward(self, f0): # f0 [B, L, 1] @audio-rate
51
+ with torch.no_grad():
52
+ sine_wavs, uv, _ = self.l_sin_gen(f0)
53
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs)) # [B, L, 1]
54
+ noise = torch.randn_like(uv) * self.sine_amp / 3
55
+ return sine_merge, noise, uv
56
+
57
+
58
+ class F0Predictor(nn.Module):
59
+ """Light causal F0 predictor: z86 [B, C, T] @86Hz -> F0 [B, T] (Hz, >=0).
60
+ Trained with GT-pitch supervision (pyworld/torchaudio) — the part that made past NSF fail."""
61
+ def __init__(self, in_ch=1024, hid=256, k=5, n_layers=4):
62
+ super().__init__()
63
+ self.k = k
64
+ chs = [in_ch] + [hid] * n_layers
65
+ self.convs = nn.ModuleList([nn.Conv1d(chs[i], chs[i + 1], k) for i in range(n_layers)])
66
+ self.out = nn.Conv1d(hid, 1, 1)
67
+
68
+ def forward(self, z): # z [B, C, T] -> [B, T]
69
+ x = z
70
+ for c in self.convs:
71
+ x = F.elu(c(F.pad(x, (self.k - 1, 0)))) # causal (left pad)
72
+ return F.softplus(self.out(x)).squeeze(1) # [B, T] >= 0 Hz
73
+
74
+
75
+ class F0BinnedPredictor(nn.Module):
76
+ """CREPE-style BINNED F0 classifier (fixes MSE-averaging -> octave mush).
77
+ z86 [B,C,T] -> per-bin activations [B, n_bins, T]; sigmoid+BCE with Gaussian soft
78
+ targets. Low total activation = unvoiced (UV gate free). Causal.
79
+ Optional reference conditioning (log-F0 mean/std of a speaker prompt) as FiLM = octave anchor (TTS)."""
80
+ def __init__(self, in_ch=1024, hid=256, k=5, n_layers=4, n_bins=256,
81
+ fmin=50.0, fmax=800.0, conf_thresh=0.5, ref_cond=False):
82
+ super().__init__()
83
+ self.k, self.n_bins, self.conf_thresh = k, n_bins, conf_thresh
84
+ chs = [in_ch] + [hid] * n_layers
85
+ self.convs = nn.ModuleList([nn.Conv1d(chs[i], chs[i + 1], k) for i in range(n_layers)])
86
+ self.out = nn.Conv1d(hid, n_bins, 1)
87
+ self.ref_cond = ref_cond
88
+ if ref_cond:
89
+ self.ref_film = nn.Linear(2, hid * 2) # [logf0_mean, logf0_std] -> gamma,beta
90
+ bin_hz = fmin * (fmax / fmin) ** torch.linspace(0, 1, n_bins)
91
+ self.register_buffer("bin_hz", bin_hz, persistent=False)
92
+ self.register_buffer("bin_log", torch.log(bin_hz), persistent=False)
93
+
94
+ def forward(self, z, ref=None): # z [B,C,T] -> logits [B, n_bins, T]
95
+ x = z
96
+ for i, c in enumerate(self.convs):
97
+ x = F.elu(c(F.pad(x, (self.k - 1, 0))))
98
+ if self.ref_cond and ref is not None and i == len(self.convs) - 1:
99
+ g, b = self.ref_film(ref).chunk(2, dim=-1) # ref [B,2] -> [B,hid]
100
+ x = x * (1 + g[..., None]) + b[..., None]
101
+ return self.out(x) # [B, n_bins, T]
102
+
103
+ def ref_logprior(self, ref_stats, width_mult=2.0):
104
+ """Gaussian log-prior over bins from reference (log-F0 mean, std) -> [1, n_bins, 1].
105
+ Added to logits before decode: anchors the octave to the speaker's range.
106
+ Only possible because this is a classifier (a regressor has nowhere to put a prior)."""
107
+ mu, sd = ref_stats
108
+ bl = self.bin_log.view(1, -1, 1)
109
+ return -0.5 * ((bl - mu) / (width_mult * max(float(sd), 1e-2))) ** 2
110
+
111
+ @torch.no_grad()
112
+ def decode(self, logits, window=4, ref_stats=None, prior_strength=0.0, width_mult=2.0):
113
+ """logits [B,n_bins,T] -> F0 [B,T] (0=unvoiced). With ref_stats+prior_strength>0 the
114
+ prediction is pulled toward the reference F0 range (kills octave derailment)."""
115
+ if ref_stats is not None and prior_strength > 0:
116
+ logits = logits + prior_strength * self.ref_logprior(ref_stats, width_mult)
117
+ act = torch.sigmoid(logits) # [B, nb, T]
118
+ B, nb, T = act.shape
119
+ conf, arg = act.max(1) # [B, T]
120
+ ii = torch.arange(nb, device=logits.device).view(1, nb, 1)
121
+ mask = ((ii >= (arg - window).unsqueeze(1)) & (ii <= (arg + window).unsqueeze(1))).float()
122
+ w = act * mask
123
+ f0log = (w * self.bin_log.view(1, nb, 1)).sum(1) / w.sum(1).clamp(min=1e-6)
124
+ f0 = torch.exp(f0log)
125
+ return torch.where(conf > self.conf_thresh, f0, torch.zeros_like(f0)) # UV gate
126
+
127
+ @staticmethod
128
+ @torch.no_grad()
129
+ def ref_stats_from_wav(wav, sr, device="cpu", conf=0.5):
130
+ """Reference speaker prompt -> (log-F0 mean, log-F0 std) for ref_logprior.
131
+ Uses torchcrepe (imported lazily). Returns None if the clip has too little voiced speech."""
132
+ import torchaudio
133
+ import torchcrepe
134
+ from torchcrepe.model import Crepe
135
+ import os as _os
136
+ if wav.dim() == 1:
137
+ wav = wav[None]
138
+ wav = wav.mean(0, keepdim=True)
139
+ w16 = torchaudio.functional.resample(wav, sr, 16000).to(device) if sr != 16000 else wav.to(device)
140
+ cache = getattr(F0BinnedPredictor, "_crepe_cache", {})
141
+ if device not in cache:
142
+ m = Crepe("tiny")
143
+ m.load_state_dict(torch.load(_os.path.join(_os.path.dirname(torchcrepe.__file__), "assets", "tiny.pth"),
144
+ map_location="cpu"))
145
+ cache[device] = m.to(device).eval()
146
+ F0BinnedPredictor._crepe_cache = cache
147
+ cm = cache[device]
148
+ hop = 186 # 16k frames matching ~86Hz z86 rate
149
+ x = F.pad(w16, (512, 512))
150
+ n = 1 + (x.shape[1] - 1024) // hop
151
+ idx = torch.arange(1024, device=device)[None, :] + hop * torch.arange(n, device=device)[:, None]
152
+ fr = x[:, idx].reshape(n, 1024)
153
+ fr = fr - fr.mean(1, keepdim=True); fr = fr / (fr.std(1, keepdim=True) + 1e-8)
154
+ act = cm(fr); pd, arg = act.max(-1)
155
+ ii = torch.arange(360, device=device)[None, :]
156
+ m = ((ii >= (arg - 4)[:, None]) & (ii <= (arg + 4)[:, None])).float()
157
+ w = act * m
158
+ binc = (w * ii).sum(-1) / w.sum(-1).clamp(min=1e-6)
159
+ f0 = 10 * 2 ** ((1997.3794084376191 + 20 * binc) / 1200)
160
+ v = pd > conf
161
+ if v.sum() < 5:
162
+ return None
163
+ lg = torch.log(f0[v].clamp(min=1.0))
164
+ return float(lg.mean()), float(lg.std().clamp(min=0.1))
165
+
166
+ def soft_targets(self, f0_gt, voiced, sigma_bins=1.5): # f0_gt [B,T] Hz, voiced [B,T] -> [B, nb, T]
167
+ lg = torch.log(f0_gt.clamp(min=1.0))
168
+ d = lg.unsqueeze(1) - self.bin_log.view(1, -1, 1) # [B, nb, T]
169
+ bw = (self.bin_log[1] - self.bin_log[0])
170
+ t = torch.exp(-0.5 * (d / (sigma_bins * bw)) ** 2)
171
+ return t * voiced.unsqueeze(1).float() # zeros where unvoiced
ecodec_fast/postvq_student.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TinyBERT-style distillation models for ECodec's post_module.
2
+
3
+ Teacher: ECodec `WindowLimitedTransformer` post_module (frozen):
4
+ 8 layers, dim 1024, n_head 16, head_dim 64, intermediate 3072, RoPE,
5
+ RMSNorm pre-norm, LayerScale, SiLU-gated FFN, windowed-causal (window=128).
6
+ Input/output dim == dim == 1024, so its input_proj/output_proj are Identity.
7
+ Uses fused F.scaled_dot_product_attention -> we monkeypatch SDPA to also
8
+ stash explicit attention probs while returning the correct attn@v output.
9
+
10
+ Student: compact LLaMA-style transformer mirroring the teacher block design
11
+ so distillation aligns head-for-head (same n_head=16):
12
+ 4 layers, dim 512, head_dim 32, intermediate 1536, EXPLICIT-softmax attention
13
+ (probs always available), windowed-causal (same window=128 as teacher),
14
+ input proj 1024->512, output proj 512->1024. ~10-15M params.
15
+
16
+ Both operate on z_q [B, 1024, T] (channels-first), transposing internally.
17
+
18
+ Phase 1 = distillation core only (no audio/GAN).
19
+ """
20
+ import sys, math, contextlib
21
+ import torch, torch.nn as nn, torch.nn.functional as F
22
+
23
+ sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
24
+ from ecodec import RMSNorm, LayerScale, precompute_freqs_cis, apply_rotary_emb
25
+
26
+ # ---- teacher facts (from ecodec.py) ----
27
+ TEACHER_DIM = 1024
28
+ TEACHER_N_HEAD = 16
29
+ TEACHER_HEAD_DIM = 64
30
+ TEACHER_N_LAYER = 8
31
+ TEACHER_WINDOW = 128
32
+ ROPE_BASE = 10000
33
+
34
+
35
+ # ===========================================================================
36
+ # Teacher wrapper: frozen post_module + per-layer hidden hooks + SDPA monkeypatch
37
+ # ===========================================================================
38
+ class TeacherExtractor:
39
+ """Wraps a frozen WindowLimitedTransformer (post_module) and, on a forward,
40
+ returns (output [B,1024,T], hidden_states list[8] of [B,T,1024],
41
+ attentions list[8] of [B,16,T,T]).
42
+
43
+ - Hidden states: forward hooks on each TransformerBlock (its output [B,T,1024]).
44
+ - Attentions: temporarily monkeypatch F.scaled_dot_product_attention so each
45
+ call computes explicit probs softmax(q@k^T/sqrt(d) + mask) and stashes them,
46
+ while still returning attn@v (numerically identical to the fused path).
47
+
48
+ Not an nn.Module on purpose (it just orchestrates a frozen module's forward).
49
+ """
50
+
51
+ def __init__(self, post_module: nn.Module):
52
+ self.post_module = post_module
53
+ self.post_module.eval()
54
+ for p in self.post_module.parameters():
55
+ p.requires_grad_(False)
56
+ # The TransformerBlocks live under post_module.layers (from Transformer base).
57
+ self.blocks = list(self.post_module.layers)
58
+ assert len(self.blocks) == TEACHER_N_LAYER, f"expected {TEACHER_N_LAYER} blocks, got {len(self.blocks)}"
59
+
60
+ @contextlib.contextmanager
61
+ def _capture(self, hiddens, attns):
62
+ # 1) hidden-state hooks on each block (output is [B,T,dim])
63
+ handles = []
64
+ for blk in self.blocks:
65
+ def hook(module, inp, out, _h=hiddens):
66
+ _h.append(out)
67
+ handles.append(blk.register_forward_hook(hook))
68
+
69
+ # 2) monkeypatch SDPA to stash explicit probs (boolean attn_mask -> -inf where False)
70
+ orig_sdpa = F.scaled_dot_product_attention
71
+
72
+ def patched_sdpa(query, key, value, attn_mask=None, dropout_p=0.0,
73
+ is_causal=False, scale=None, **kw):
74
+ d = query.shape[-1]
75
+ sc = (1.0 / math.sqrt(d)) if scale is None else scale
76
+ logits = (query.float() @ key.float().transpose(-2, -1)) * sc # [B,H,T,T]
77
+ if attn_mask is not None:
78
+ if attn_mask.dtype == torch.bool:
79
+ logits = logits.masked_fill(~attn_mask, float("-inf"))
80
+ else:
81
+ logits = logits + attn_mask
82
+ elif is_causal:
83
+ T = query.shape[-2]
84
+ cm = torch.ones(T, T, dtype=torch.bool, device=query.device).tril()
85
+ logits = logits.masked_fill(~cm, float("-inf"))
86
+ probs = torch.softmax(logits, dim=-1)
87
+ attns.append(probs.detach()) # teacher target -> no grad
88
+ return (probs.type_as(value) @ value)
89
+
90
+ F.scaled_dot_product_attention = patched_sdpa
91
+ try:
92
+ yield
93
+ finally:
94
+ F.scaled_dot_product_attention = orig_sdpa
95
+ for h in handles:
96
+ h.remove()
97
+
98
+ @torch.no_grad()
99
+ def __call__(self, z_q): # z_q [B,1024,T]
100
+ hiddens, attns = [], []
101
+ with self._capture(hiddens, attns):
102
+ out = self.post_module(z_q) # [B,1024,T]
103
+ # blocks fire in order -> lists are layer-ordered (0..7)
104
+ return out, hiddens, attns
105
+
106
+
107
+ # ===========================================================================
108
+ # Student transformer
109
+ # ===========================================================================
110
+ class StudentAttention(nn.Module):
111
+ """Same layout as teacher Attention (wqkv fused, wo), but EXPLICIT softmax so
112
+ the [B,n_head,T,T] probs are directly returned. n_head matches the teacher."""
113
+
114
+ def __init__(self, dim, n_head, head_dim, attn_dropout_rate=0.0):
115
+ super().__init__()
116
+ self.n_head = n_head
117
+ self.head_dim = head_dim
118
+ # n_local_heads == n_head (no GQA), matching the teacher
119
+ self.wqkv = nn.Linear(dim, 3 * n_head * head_dim, bias=False)
120
+ self.wo = nn.Linear(n_head * head_dim, dim, bias=False)
121
+ self.attn_dropout_rate = attn_dropout_rate
122
+
123
+ def forward(self, x, freqs_cis, mask):
124
+ bsz, seqlen, _ = x.shape
125
+ kv = self.n_head * self.head_dim
126
+ q, k, v = self.wqkv(x).split([kv, kv, kv], dim=-1)
127
+ q = q.view(bsz, seqlen, self.n_head, self.head_dim)
128
+ k = k.view(bsz, seqlen, self.n_head, self.head_dim)
129
+ v = v.view(bsz, seqlen, self.n_head, self.head_dim)
130
+ q = apply_rotary_emb(q, freqs_cis)
131
+ k = apply_rotary_emb(k, freqs_cis)
132
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v)) # [B,H,T,hd]
133
+
134
+ logits = (q.float() @ k.float().transpose(-2, -1)) / math.sqrt(self.head_dim) # [B,H,T,T]
135
+ if mask is not None:
136
+ logits = logits.masked_fill(~mask, float("-inf"))
137
+ probs = torch.softmax(logits, dim=-1)
138
+ attn = probs.type_as(v)
139
+ if self.training and self.attn_dropout_rate > 0:
140
+ attn = F.dropout(attn, self.attn_dropout_rate)
141
+ y = attn @ v # [B,H,T,hd]
142
+ y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.n_head * self.head_dim)
143
+ return self.wo(y), probs # probs (pre-dropout) = distill target
144
+
145
+
146
+ class StudentFFN(nn.Module):
147
+ def __init__(self, dim, intermediate, dropout_rate=0.0):
148
+ super().__init__()
149
+ self.w1 = nn.Linear(dim, intermediate, bias=False)
150
+ self.w3 = nn.Linear(dim, intermediate, bias=False)
151
+ self.w2 = nn.Linear(intermediate, dim, bias=False)
152
+ self.dropout = nn.Dropout(dropout_rate)
153
+
154
+ def forward(self, x):
155
+ return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
156
+
157
+
158
+ class StudentBlock(nn.Module):
159
+ """Mirrors teacher TransformerBlock: pre-RMSNorm -> attn -> LayerScale -> res;
160
+ pre-RMSNorm -> SiLU-gated FFN -> LayerScale -> res."""
161
+
162
+ def __init__(self, dim, n_head, head_dim, intermediate, norm_eps=1e-5,
163
+ dropout_rate=0.0, attn_dropout_rate=0.0):
164
+ super().__init__()
165
+ self.attention = StudentAttention(dim, n_head, head_dim, attn_dropout_rate)
166
+ self.feed_forward = StudentFFN(dim, intermediate, dropout_rate)
167
+ self.attention_norm = RMSNorm(dim, eps=norm_eps)
168
+ self.ffn_norm = RMSNorm(dim, eps=norm_eps)
169
+ self.attention_layer_scale = LayerScale(dim, inplace=False)
170
+ self.ffn_layer_scale = LayerScale(dim, inplace=False)
171
+
172
+ def forward(self, x, freqs_cis, mask):
173
+ a, probs = self.attention(self.attention_norm(x), freqs_cis, mask)
174
+ h = x + self.attention_layer_scale(a)
175
+ out = h + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(h)))
176
+ return out, probs
177
+
178
+
179
+ class StudentTransformer(nn.Module):
180
+ """Compact distilled post_module. Operates on z_q [B,1024,T] (channels-first).
181
+
182
+ forward -> (output [B,1024,T],
183
+ hidden_states list[n_layer] of [B,T,dim],
184
+ attentions list[n_layer] of [B,n_head,T,T]).
185
+ """
186
+
187
+ def __init__(self, input_dim=1024, dim=512, n_layer=4, n_head=16, head_dim=32,
188
+ intermediate=1536, window_size=TEACHER_WINDOW, block_size=4096,
189
+ rope_base=ROPE_BASE, norm_eps=1e-5, causal=True,
190
+ dropout_rate=0.0, attn_dropout_rate=0.0):
191
+ super().__init__()
192
+ assert dim == n_head * head_dim, f"{dim} != {n_head}*{head_dim}"
193
+ self.dim = dim
194
+ self.window_size = window_size
195
+ self.causal = causal
196
+ self.input_proj = nn.Linear(input_dim, dim)
197
+ self.output_proj = nn.Linear(dim, input_dim)
198
+ self.nq_emb = nn.Embedding(11, input_dim) # кондишен на число кодбуков (nq 1..10); 0 не юзается
199
+ nn.init.zeros_(self.nq_emb.weight) # zero-init: на старте не возмущает вход
200
+ self.layers = nn.ModuleList(
201
+ StudentBlock(dim, n_head, head_dim, intermediate, norm_eps,
202
+ dropout_rate, attn_dropout_rate)
203
+ for _ in range(n_layer)
204
+ )
205
+ self.norm = RMSNorm(dim, eps=norm_eps)
206
+ freqs_cis = precompute_freqs_cis(block_size, head_dim, rope_base, dtype=torch.float32)
207
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
208
+
209
+ def _make_mask(self, T, device):
210
+ # same windowed-causal mask shape the teacher uses: [1,1,T,T] bool
211
+ if not self.causal:
212
+ return torch.ones(1, 1, T, T, dtype=torch.bool, device=device)
213
+ mask = torch.ones(T, T, dtype=torch.bool, device=device).tril()
214
+ if self.window_size is not None:
215
+ row = torch.arange(T, device=device).view(-1, 1)
216
+ valid = (row - self.window_size + 1).clamp(min=0)
217
+ col = torch.arange(T, device=device)
218
+ mask = (col >= valid) & mask
219
+ return mask[None, None]
220
+
221
+ def forward(self, z_q, nq=None): # z_q [B,1024,T]; nq: int число кодбуков (опц.)
222
+ if nq is not None:
223
+ z_q = z_q + self.nq_emb.weight[nq][None, :, None] # кондишен на nq
224
+ x = z_q.transpose(1, 2) # [B,T,1024]
225
+ x = self.input_proj(x) # [B,T,dim]
226
+ T = x.shape[1]
227
+ freqs_cis = self.freqs_cis[:T].to(x.device)
228
+ mask = self._make_mask(T, x.device)
229
+ hiddens, attns = [], []
230
+ for layer in self.layers:
231
+ x, probs = layer(x, freqs_cis, mask)
232
+ hiddens.append(x) # block output [B,T,dim]
233
+ attns.append(probs) # [B,n_head,T,T]
234
+ x = self.norm(x)
235
+ out = self.output_proj(x).transpose(1, 2) # [B,1024,T]
236
+ return out, hiddens, attns
237
+
238
+
239
+ if __name__ == "__main__":
240
+ torch.manual_seed(0)
241
+ s = StudentTransformer()
242
+ n = sum(p.numel() for p in s.parameters())
243
+ print(f"Student params: {n/1e6:.2f}M ({n:,})")
244
+ z = torch.randn(2, 1024, 30)
245
+ out, hs, at = s(z)
246
+ print("out", tuple(out.shape), "| hiddens", len(hs), tuple(hs[0].shape),
247
+ "| attns", len(at), tuple(at[0].shape))
248
+ # attention probs should sum to 1 over the key axis
249
+ print("attn row-sum (should be ~1):", float(at[0][0, 0, -1].sum()))
ecodec_quantizer_slim.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dc36ea6b3831aa34a5101bcbe3d29722b44f62894187b9ecdf259370a25efb2
3
+ size 85218818
nano_nsf_v2_60k.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ae85e0f1ca78fecd3a583b75b2fe57665941d59949993a0c8460abb73b8ea59
3
+ size 189943256
postvq_student_90k.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:409c91e25582d0ca95d8d3140ffb35f344ef9d4731580ad71c55901d3505fa59
3
+ size 58822546
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.1
2
+ torchaudio>=2.1
3
+ numpy
4
+ # optional: only for NanoDecoderV2.speaker_ref() (pitch anchoring, mode B)
5
+ # torchcrepe