""" ECodec: Standalone DAC-based VQVAE audio codec. No external dependencies beyond torch. All utilities are inlined. Compatible with ecodec/codec.pth checkpoint. Architecture: Encoder: Conv1d(1,64) -> 4 EncoderBlocks [2,4,8,8] -> Conv1d(1024,1024) Quantizer: downsample [2,2] -> pre_module (8-layer transformer) -> semantic VQ (1 codebook, 4096) + residual VQ (9 codebooks, 1024) -> post_module (8-layer transformer) -> upsample [2,2] Decoder: Conv1d(1024,1536) -> 4 DecoderBlocks [8,8,4,2] -> Conv1d(96,1) -> Tanh """ from __future__ import annotations import math import typing as tp from contextlib import nullcontext from typing import Optional, Union import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn.utils.parametrizations import weight_norm as new_weight_norm from torch.nn.utils.parametrize import remove_parametrizations from torch.nn.utils import weight_norm as old_weight_norm # --------------------------------------------------------------------------- # Utility functions # --------------------------------------------------------------------------- def find_multiple(n: int, k: int) -> int: if n % k == 0: return n return n + k - (n % k) def unpad1d(x: Tensor, paddings: tp.Tuple[int, int]) -> Tensor: padding_left, padding_right = paddings assert padding_left >= 0 and padding_right >= 0 assert (padding_left + padding_right) <= x.shape[-1] end = x.shape[-1] - padding_right return x[..., padding_left:end] def get_extra_padding_for_conv1d( x: Tensor, kernel_size: int, stride: int, padding_total: int = 0 ) -> int: length = x.shape[-1] n_frames = (length - kernel_size + padding_total) / stride + 1 ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total) return ideal_length - length def pad1d( x: Tensor, paddings: tp.Tuple[int, int], mode: str = "zeros", value: float = 0.0, ) -> Tensor: length = x.shape[-1] padding_left, padding_right = paddings assert padding_left >= 0 and padding_right >= 0 if mode == "reflect": max_pad = max(padding_left, padding_right) extra_pad = 0 if length <= max_pad: extra_pad = max_pad - length + 1 x = F.pad(x, (0, extra_pad)) padded = F.pad(x, paddings, mode, value) end = padded.shape[-1] - extra_pad return padded[..., :end] else: return F.pad(x, paddings, mode, value) def precompute_freqs_cis( seq_len: int, n_elem: int, base: int = 10000, dtype: torch.dtype = torch.bfloat16 ) -> Tensor: freqs = 1.0 / ( base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem) ) t = torch.arange(seq_len, device=freqs.device) freqs = torch.outer(t, freqs) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1) return cache.to(dtype=dtype) def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor: xshaped = x.float().reshape(*x.shape[:-1], -1, 2) freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2) x_out2 = torch.stack( [ xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1], xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1], ], -1, ) x_out2 = x_out2.flatten(3) return x_out2.type_as(x) def init_weights(m: nn.Module) -> None: if isinstance(m, nn.Conv1d): nn.init.trunc_normal_(m.weight, std=0.02) nn.init.constant_(m.bias, 0) # --------------------------------------------------------------------------- # Snake1d activation # --------------------------------------------------------------------------- class Snake1d(nn.Module): """Snake activation: x + (1/alpha) * sin^2(alpha * x)""" def __init__(self, channels: int) -> None: super().__init__() self.alpha = nn.Parameter(torch.ones(1, channels, 1)) def forward(self, x: Tensor) -> Tensor: return x + (1.0 / self.alpha) * torch.sin(self.alpha * x) ** 2 # --------------------------------------------------------------------------- # Causal convolutions (new-style weight_norm via parametrizations) # --------------------------------------------------------------------------- class CausalConvNet(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, dilation: int = 1, stride: int = 1, groups: int = 1, padding: int = None, ) -> None: super().__init__() self.conv = nn.Conv1d( in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, groups=groups, ) self.stride = stride self.kernel_size = (kernel_size - 1) * dilation + 1 self.dilation = dilation self.padding = self.kernel_size - self.stride def forward(self, x: Tensor) -> Tensor: pad = self.padding extra_padding = get_extra_padding_for_conv1d( x, self.kernel_size, self.stride, pad ) x = pad1d(x, (pad, extra_padding), mode="constant", value=0) return self.conv(x).contiguous() def weight_norm(self, name: str = "weight", dim: int = 0) -> "CausalConvNet": self.conv = new_weight_norm(self.conv, name=name, dim=dim) return self def remove_weight_norm(self) -> "CausalConvNet": remove_parametrizations(self.conv, "weight") return self class CausalTransConvNet(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, dilation: int = 1, stride: int = 1, padding: int = None, ) -> None: super().__init__() self.conv = nn.ConvTranspose1d( in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, ) self.stride = stride self.kernel_size = kernel_size def forward(self, x: Tensor) -> Tensor: x = self.conv(x) pad = self.kernel_size - self.stride padding_right = math.ceil(pad) padding_left = pad - padding_right x = unpad1d(x, (padding_left, padding_right)) return x.contiguous() def weight_norm(self, name: str = "weight", dim: int = 0) -> "CausalTransConvNet": self.conv = new_weight_norm(self.conv, name=name, dim=dim) return self def remove_weight_norm(self) -> "CausalTransConvNet": remove_parametrizations(self.conv, "weight") return self def CausalWNConv1d(*args, **kwargs) -> CausalConvNet: return CausalConvNet(*args, **kwargs).weight_norm() def CausalWNConvTranspose1d(*args, **kwargs) -> CausalTransConvNet: return CausalTransConvNet(*args, **kwargs).weight_norm() # --------------------------------------------------------------------------- # Transformer building blocks # --------------------------------------------------------------------------- class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-5) -> None: super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def _norm(self, x: Tensor) -> Tensor: return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps) def forward(self, x: Tensor) -> Tensor: output = self._norm(x.float()).type_as(x) return output * self.weight class LayerScale(nn.Module): def __init__( self, dim: int, init_values: Union[float, Tensor] = 1e-2, inplace: bool = False, ) -> None: super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x: Tensor) -> Tensor: return x.mul_(self.gamma) if self.inplace else x * self.gamma class Attention(nn.Module): def __init__( self, dim: int, n_head: int, n_local_heads: int, head_dim: int, attn_dropout_rate: float = 0.1, ) -> None: super().__init__() assert dim % n_head == 0 total_head_dim = (n_head + 2 * n_local_heads) * head_dim self.wqkv = nn.Linear(dim, total_head_dim, bias=False) self.wo = nn.Linear(head_dim * n_head, dim, bias=False) self.kv_cache = None self.n_head = n_head self.head_dim = head_dim self.n_local_heads = n_local_heads self.dim = dim self.attn_dropout_rate = attn_dropout_rate self.kv_repeat = n_head // n_local_heads def forward( self, x: Tensor, freqs_cis: Tensor, mask: Tensor, input_pos: Optional[Tensor] = None, ) -> Tensor: bsz, seqlen, _ = x.shape kv_size = self.n_local_heads * self.head_dim q, k, v = self.wqkv(x).split([kv_size, kv_size, kv_size], dim=-1) q = q.view(bsz, seqlen, self.n_head, self.head_dim) k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim) v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim) q = apply_rotary_emb(q, freqs_cis) k = apply_rotary_emb(k, freqs_cis) q, k, v = (t.transpose(1, 2) for t in (q, k, v)) if self.kv_repeat > 1: k = k.repeat_interleave(self.kv_repeat, dim=1) v = v.repeat_interleave(self.kv_repeat, dim=1) y = F.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_dropout_rate if self.training else 0.0, attn_mask=mask, ) y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.head_dim * self.n_head) return self.wo(y) class FeedForward(nn.Module): def __init__(self, dim: int, intermediate_size: int, dropout_rate: float = 0.1) -> None: super().__init__() self.w1 = nn.Linear(dim, intermediate_size, bias=False) self.w3 = nn.Linear(dim, intermediate_size, bias=False) self.w2 = nn.Linear(intermediate_size, dim, bias=False) self.dropout = nn.Dropout(dropout_rate) def forward(self, x: Tensor) -> Tensor: return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x))) class TransformerBlock(nn.Module): def __init__( self, dim: int, n_head: int, n_local_heads: int, head_dim: int, intermediate_size: int, norm_eps: float = 1e-5, dropout_rate: float = 0.1, attn_dropout_rate: float = 0.1, ) -> None: super().__init__() self.attention = Attention(dim, n_head, n_local_heads, head_dim, attn_dropout_rate) self.feed_forward = FeedForward(dim, intermediate_size, dropout_rate) self.ffn_norm = RMSNorm(dim, eps=norm_eps) self.attention_norm = RMSNorm(dim, eps=norm_eps) self.attention_layer_scale = LayerScale(dim, inplace=True) self.ffn_layer_scale = LayerScale(dim, inplace=True) def forward(self, x: Tensor, input_pos: Tensor, freqs_cis: Tensor, mask: Tensor) -> Tensor: h = x + self.attention_layer_scale( self.attention(self.attention_norm(x), freqs_cis, mask, input_pos) ) out = h + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(h))) return out class Transformer(nn.Module): def __init__( self, n_layer: int, n_head: int, dim: int, intermediate_size: int, head_dim: int = 64, block_size: int = 4096, rope_base: float = 10000, norm_eps: float = 1e-5, dropout_rate: float = 0.1, attn_dropout_rate: float = 0.1, ) -> None: super().__init__() self.n_layer = n_layer self.n_head = n_head self.dim = dim self.head_dim = head_dim self.block_size = block_size n_local_heads = n_head self.layers = nn.ModuleList( TransformerBlock( dim, n_head, n_local_heads, head_dim, intermediate_size, norm_eps, dropout_rate, attn_dropout_rate, ) for _ in range(n_layer) ) self.norm = RMSNorm(dim, eps=norm_eps) freqs_cis = precompute_freqs_cis(block_size, head_dim, rope_base) self.register_buffer("freqs_cis", freqs_cis) causal_mask = torch.tril(torch.ones(block_size, block_size, dtype=torch.bool)) self.register_buffer("causal_mask", causal_mask) def forward(self, x: Tensor, input_pos: Tensor, mask: Optional[Tensor] = None) -> Tensor: freqs_cis = self.freqs_cis[input_pos] if mask is None: mask = self.causal_mask[None, None, input_pos] mask = mask[..., input_pos] for layer in self.layers: x = layer(x, input_pos, freqs_cis, mask) x = self.norm(x) return x class WindowLimitedTransformer(Transformer): """Transformer with window-limited causal attention.""" def __init__( self, n_layer: int, n_head: int, dim: int, intermediate_size: int, head_dim: int = 64, block_size: int = 4096, rope_base: float = 10000, norm_eps: float = 1e-5, dropout_rate: float = 0.1, attn_dropout_rate: float = 0.1, input_dim: int = 1024, window_size: Optional[int] = None, causal: bool = True, channels_first: bool = True, ) -> None: super().__init__( n_layer=n_layer, n_head=n_head, dim=dim, intermediate_size=intermediate_size, head_dim=head_dim, block_size=block_size, rope_base=rope_base, norm_eps=norm_eps, dropout_rate=dropout_rate, attn_dropout_rate=attn_dropout_rate, ) self.window_size = window_size self.causal = causal self.channels_first = channels_first # Parent's causal_mask buffer is unused (we compute windowed mask in forward) if "causal_mask" in self._buffers: del self._buffers["causal_mask"] self.look_ahead_conv = nn.Identity() self.input_proj = ( nn.Linear(input_dim, dim) if input_dim != dim else nn.Identity() ) self.output_proj = ( nn.Linear(dim, input_dim) if input_dim != dim else nn.Identity() ) def _make_mask(self, max_length: int, device: torch.device = None) -> Tensor: if self.causal: mask = torch.tril(torch.ones(max_length, max_length, dtype=torch.bool, device=device)) if self.window_size is not None: row_indices = torch.arange(max_length, device=device).view(-1, 1) valid_range = (row_indices - self.window_size + 1).clamp(min=0) column_indices = torch.arange(max_length, device=device) mask = (column_indices >= valid_range) & mask else: mask = torch.ones(max_length, max_length, dtype=torch.bool, device=device) return mask[None, None] def forward(self, x: Tensor, x_lens: Optional[Tensor] = None) -> Tensor: if self.channels_first: x = x.transpose(1, 2) x = self.input_proj(x) x = self.look_ahead_conv(x) input_pos = torch.arange(x.shape[1], device=x.device) mask = self._make_mask(x.shape[1], device=x.device) x = super().forward(x, input_pos, mask) x = self.output_proj(x) if self.channels_first: x = x.transpose(1, 2) return x # --------------------------------------------------------------------------- # ConvNeXt Block (used in quantizer downsample/upsample) # --------------------------------------------------------------------------- class ConvNeXtBlock(nn.Module): def __init__( self, dim: int, layer_scale_init_value: float = 1e-6, mlp_ratio: float = 4.0, kernel_size: int = 7, dilation: int = 1, ) -> None: super().__init__() self.dwconv = CausalConvNet(dim, dim, kernel_size=kernel_size, groups=dim, dilation=dilation) self.norm = nn.LayerNorm(dim, eps=1e-6) self.pwconv1 = nn.Linear(dim, int(mlp_ratio * dim)) self.act = nn.GELU() self.pwconv2 = nn.Linear(int(mlp_ratio * dim), dim) self.gamma = ( nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True) if layer_scale_init_value > 0 else None ) def forward(self, x: Tensor, apply_residual: bool = True) -> Tensor: residual = x x = self.dwconv(x) x = x.permute(0, 2, 1) x = self.norm(x) x = self.pwconv1(x) x = self.act(x) x = self.pwconv2(x) if self.gamma is not None: x = self.gamma * x x = x.permute(0, 2, 1) if apply_residual: x = residual + x return x # --------------------------------------------------------------------------- # Encoder / Decoder blocks # --------------------------------------------------------------------------- class ResidualUnit(nn.Module): def __init__(self, dim: int = 16, dilation: int = 1, causal: bool = True) -> None: super().__init__() pad = ((7 - 1) * dilation) // 2 self.block = nn.Sequential( Snake1d(dim), CausalWNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad), Snake1d(dim), CausalWNConv1d(dim, dim, kernel_size=1), ) self.causal = causal def forward(self, x: Tensor) -> Tensor: y = self.block(x) pad = x.shape[-1] - y.shape[-1] if pad > 0: if self.causal: x = x[..., :-pad] else: x = x[..., pad // 2 : -pad // 2] return x + y class EncoderBlock(nn.Module): def __init__( self, dim: int = 16, stride: int = 1, causal: bool = True, n_t_layer: int = 0, ) -> None: super().__init__() transformer_module: nn.Module if n_t_layer == 0: transformer_module = nn.Identity() else: transformer_module = WindowLimitedTransformer( n_layer=n_t_layer, n_head=dim // 64, dim=dim, intermediate_size=dim * 3, head_dim=64, block_size=16384, dropout_rate=0.1, attn_dropout_rate=0.1, input_dim=dim, window_size=512, causal=causal, channels_first=True, ) self.block = nn.Sequential( ResidualUnit(dim // 2, dilation=1, causal=causal), ResidualUnit(dim // 2, dilation=3, causal=causal), ResidualUnit(dim // 2, dilation=9, causal=causal), Snake1d(dim // 2), CausalWNConv1d( dim // 2, dim, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2), ), transformer_module, ) def forward(self, x: Tensor) -> Tensor: return self.block(x) class Encoder(nn.Module): def __init__( self, d_model: int = 64, strides: list = [2, 4, 8, 8], d_latent: int = 1024, n_transformer_layers: list = [0, 0, 0, 4], causal: bool = True, ) -> None: super().__init__() self.block = [CausalWNConv1d(1, d_model, kernel_size=7, padding=3)] for stride, n_t_layer in zip(strides, n_transformer_layers): d_model *= 2 self.block.append( EncoderBlock(d_model, stride=stride, causal=causal, n_t_layer=n_t_layer) ) self.block.append(Snake1d(d_model)) self.block.append(CausalWNConv1d(d_model, d_latent, kernel_size=3, padding=1)) self.block = nn.Sequential(*self.block) self.enc_dim = d_model def forward(self, x: Tensor) -> Tensor: return self.block(x) class DecoderBlock(nn.Module): def __init__( self, input_dim: int = 16, output_dim: int = 8, stride: int = 1, causal: bool = True, n_t_layer: int = 0, ) -> None: super().__init__() self.block = nn.Sequential( Snake1d(input_dim), CausalWNConvTranspose1d( input_dim, output_dim, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2), ), ResidualUnit(output_dim, dilation=1, causal=causal), ResidualUnit(output_dim, dilation=3, causal=causal), ResidualUnit(output_dim, dilation=9, causal=causal), ) def forward(self, x: Tensor) -> Tensor: return self.block(x) class Decoder(nn.Module): def __init__( self, input_channel: int = 1024, channels: int = 1536, rates: list = [8, 8, 4, 2], d_out: int = 1, causal: bool = True, n_transformer_layers: list = [0, 0, 0, 0], ) -> None: super().__init__() layers: list[nn.Module] = [CausalWNConv1d(input_channel, channels, kernel_size=7, padding=3)] output_dim = channels for i, (stride, n_t_layer) in enumerate(zip(rates, n_transformer_layers)): input_dim = channels // 2**i output_dim = channels // 2 ** (i + 1) layers.append( DecoderBlock(input_dim, output_dim, stride, causal=causal, n_t_layer=n_t_layer) ) layers.append(Snake1d(output_dim)) layers.append(CausalWNConv1d(output_dim, d_out, kernel_size=7, padding=3)) layers.append(nn.Tanh()) self.model = nn.Sequential(*layers) def forward(self, x: Tensor) -> Tensor: return self.model(x) # --------------------------------------------------------------------------- # VQ (Vector Quantize) — uses OLD-style weight_norm for checkpoint compat # --------------------------------------------------------------------------- def _WNConv1d_old(in_channels: int, out_channels: int, kernel_size: int) -> nn.Conv1d: """Conv1d with old-style weight_norm (weight_g + weight_v keys).""" return old_weight_norm(nn.Conv1d(in_channels, out_channels, kernel_size)) class VectorQuantize(nn.Module): def __init__( self, input_dim: int = 1024, codebook_size: int = 1024, codebook_dim: int = 8, ) -> None: super().__init__() self.in_proj = _WNConv1d_old(input_dim, codebook_dim, 1) self.out_proj = _WNConv1d_old(codebook_dim, input_dim, 1) self.codebook = nn.Embedding(codebook_size, codebook_dim) def forward(self, z: Tensor) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """ z: (B, D, T) Returns: (z_q, codes, latents, commitment_loss, codebook_loss) """ z_e = self.in_proj(z) # (B, codebook_dim, T) z_e_t = z_e.permute(0, 2, 1) # (B, T, codebook_dim) # Nearest neighbor lookup (fp32 for numerical stability under autocast) with torch.no_grad(): z_e_f = z_e_t.float() w_f = self.codebook.weight.float() d = ( z_e_f.pow(2).sum(-1, keepdim=True) + w_f.pow(2).sum(-1) - 2 * z_e_f @ w_f.t() ) indices = d.argmin(-1) # (B, T) z_q_t = self.codebook(indices) # (B, T, codebook_dim) z_q = z_q_t.permute(0, 2, 1) # (B, codebook_dim, T) # Straight-through estimator commitment_loss = F.mse_loss(z_e, z_q.detach()) codebook_loss = F.mse_loss(z_q, z_e.detach()) z_q_st = z_e + (z_q - z_e).detach() z_q_out = self.out_proj(z_q_st) # (B, D, T) return z_q_out, indices.unsqueeze(1), z_e, commitment_loss, codebook_loss def from_codes(self, codes: Tensor) -> tp.Tuple[Tensor, Tensor]: """ codes: (B, 1, T) Returns: (z_q, z_e) """ indices = codes.squeeze(1) # (B, T) z_q_t = self.codebook(indices) # (B, T, codebook_dim) z_q = z_q_t.permute(0, 2, 1) # (B, codebook_dim, T) z_q_out = self.out_proj(z_q) # (B, D, T) return z_q_out, z_q class ResidualVectorQuantize(nn.Module): def __init__( self, input_dim: int = 1024, n_codebooks: int = 9, codebook_size: int = 1024, codebook_dim: int = 8, quantizer_dropout: float = 0.0, ) -> None: super().__init__() self.n_codebooks = n_codebooks self._codebook_size = codebook_size self.quantizer_dropout = quantizer_dropout self.quantizers = nn.ModuleList( [VectorQuantize(input_dim, codebook_size, codebook_dim) for _ in range(n_codebooks)] ) @property def codebook_size(self) -> int: return self._codebook_size def forward( self, z: Tensor, n_quantizers: Optional[int] = None, **kwargs ) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """ z: (B, D, T) Returns: (z_q, codes, latents, commitment_loss, codebook_loss) """ z_q = torch.zeros_like(z) residual = z.clone() all_codes = [] all_latents = [] commitment_loss = torch.tensor(0.0, device=z.device) codebook_loss = torch.tensor(0.0, device=z.device) n_q = n_quantizers if n_quantizers is not None else self.n_codebooks if self.training: n_dropout = torch.randint(1, n_q + 1, (1,)).item() if self.quantizer_dropout > 0 else n_q else: n_dropout = n_q for i, quantizer in enumerate(self.quantizers[:n_q]): z_q_i, codes_i, latents_i, c_loss, cb_loss = quantizer(residual) residual = residual - z_q_i if i < n_dropout: z_q = z_q + z_q_i commitment_loss = commitment_loss + c_loss codebook_loss = codebook_loss + cb_loss all_codes.append(codes_i) all_latents.append(latents_i) codes = torch.cat(all_codes, dim=1) # (B, n_codebooks, T) latents = torch.cat(all_latents, dim=1) # (B, n_codebooks*codebook_dim, T) return z_q, codes, latents, commitment_loss, codebook_loss def from_codes(self, codes: Tensor) -> tp.Tuple[Tensor, Tensor]: """ codes: (B, n_codebooks, T) Returns: (z_q, None) """ z_q = torch.zeros( codes.shape[0], self.quantizers[0].out_proj.out_channels, codes.shape[2], device=codes.device, dtype=torch.float32, ) for i, quantizer in enumerate(self.quantizers): if i >= codes.shape[1]: break z_q_i, _ = quantizer.from_codes(codes[:, i : i + 1]) z_q = z_q + z_q_i return z_q, None # --------------------------------------------------------------------------- # DownsampleResidualVectorQuantize # --------------------------------------------------------------------------- class DownsampleResidualVectorQuantize(nn.Module): def __init__( self, input_dim: int = 1024, n_codebooks: int = 9, codebook_dim: int = 8, quantizer_dropout: float = 0.5, codebook_size: int = 1024, semantic_codebook_size: int = 4096, downsample_factor: tp.Tuple[int, ...] = (2, 2), downsample_dims: tp.Optional[tp.Tuple[int, ...]] = None, pre_module: Optional[nn.Module] = None, post_module: Optional[nn.Module] = None, ) -> None: super().__init__() if downsample_dims is None: downsample_dims = [input_dim for _ in range(len(downsample_factor))] all_dims = (input_dim,) + tuple(downsample_dims) self.semantic_quantizer = ResidualVectorQuantize( input_dim=input_dim, n_codebooks=1, codebook_size=semantic_codebook_size, codebook_dim=codebook_dim, quantizer_dropout=0.0, ) self.quantizer = ResidualVectorQuantize( input_dim=input_dim, n_codebooks=n_codebooks, codebook_size=codebook_size, codebook_dim=codebook_dim, quantizer_dropout=quantizer_dropout, ) self.downsample_factor = downsample_factor self.downsample_dims = downsample_dims self.downsample = nn.Sequential( *[ nn.Sequential( CausalConvNet(all_dims[idx], all_dims[idx + 1], kernel_size=factor, stride=factor), ConvNeXtBlock(dim=all_dims[idx + 1]), ) for idx, factor in enumerate(downsample_factor) ] ) self.upsample = nn.Sequential( *[ nn.Sequential( CausalTransConvNet(all_dims[idx + 1], all_dims[idx], kernel_size=factor, stride=factor), ConvNeXtBlock(dim=all_dims[idx]), ) for idx, factor in reversed(list(enumerate(downsample_factor))) ] ) self.pre_module = pre_module if pre_module is not None else nn.Identity() self.post_module = post_module if post_module is not None else nn.Identity() self._init_ds_us_weights() def _init_ds_us_weights(self) -> None: for m in list(self.downsample.modules()) + list(self.upsample.modules()): if isinstance(m, (nn.Conv1d, nn.Linear)): nn.init.trunc_normal_(m.weight, std=0.02) if m.bias is not None: nn.init.constant_(m.bias, 0) def forward( self, z: Tensor, n_quantizers: Optional[int] = None, **kwargs ) -> tp.Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: original_shape = z.shape z = self.downsample(z) z = self.pre_module(z) semantic_z, semantic_codes, semantic_latents, sc_loss, scb_loss = self.semantic_quantizer(z) residual_z = z - semantic_z residual_z, codes, latents, c_loss, cb_loss = self.quantizer(residual_z, n_quantizers=n_quantizers) z = semantic_z + residual_z commitment_loss = c_loss + sc_loss codebook_loss = cb_loss + scb_loss codes = torch.cat([semantic_codes, codes], dim=1) latents = torch.cat([semantic_latents, latents], dim=1) z = self.post_module(z) z = self.upsample(z) diff = original_shape[-1] - z.shape[-1] if diff > 0: z = F.pad(z, (abs(diff), 0)) elif diff < 0: z = z[..., abs(diff):] return z, codes, latents, commitment_loss, codebook_loss def encode_only( self, z: Tensor, n_quantizers: tp.Optional[int] = None ) -> Tensor: """Encode to codes only, skipping post_module and upsample.""" z = self.downsample(z) z = self.pre_module(z) semantic_z, semantic_codes, _, _, _ = self.semantic_quantizer(z) residual_z = z - semantic_z _, codes, _, _, _ = self.quantizer(residual_z, n_quantizers=n_quantizers) return torch.cat([semantic_codes, codes], dim=1) def decode(self, indices: Tensor) -> Tensor: new_indices = torch.zeros_like(indices) new_indices[:, 0] = torch.clamp(indices[:, 0], max=self.semantic_quantizer.codebook_size - 1) new_indices[:, 1:] = torch.clamp(indices[:, 1:], max=self.quantizer.codebook_size - 1) z_q_semantic, _ = self.semantic_quantizer.from_codes(new_indices[:, :1]) z_q_residual, _ = self.quantizer.from_codes(new_indices[:, 1:]) z_q = z_q_semantic + z_q_residual z_q = self.post_module(z_q) z_q = self.upsample(z_q) return z_q # --------------------------------------------------------------------------- # ECodec — top-level model # --------------------------------------------------------------------------- class ECodec(nn.Module): """ ECodec audio codec. Sample rate: 44100 Hz Hop length: 512 (encoder strides: 2*4*8*8 = 512) Latent dim: 1024 Codebooks: 1 semantic (4096 entries) + 9 residual (1024 entries each) = 10 total Quantizer downsamples by 4x (factors [2,2]), so code rate = 44100 / 512 / 4 ~ 21.5 Hz """ def __init__(self) -> None: super().__init__() # ---- Hardcoded config ---- encoder_dim = 64 encoder_rates = [2, 4, 8, 8] encoder_transformer_layers = [0, 0, 0, 4] latent_dim = 1024 decoder_dim = 1536 decoder_rates = [8, 8, 4, 2] decoder_transformer_layers = [0, 0, 0, 0] sample_rate = 44100 n_codebooks = 9 codebook_size = 1024 codebook_dim = 8 semantic_codebook_size = 4096 downsample_factor = (2, 2) self.sample_rate = sample_rate self.hop_length = 1 for r in encoder_rates: self.hop_length *= r # = 512 self.latent_dim = latent_dim self.frame_length = self.hop_length * 4 # = 2048 # ---- Encoder ---- self.encoder = Encoder( d_model=encoder_dim, strides=encoder_rates, d_latent=latent_dim, n_transformer_layers=encoder_transformer_layers, causal=True, ) # ---- Quantizer ---- # Pre/post modules are WindowLimitedTransformers with window_size=128 q_pre = WindowLimitedTransformer( n_layer=8, n_head=16, dim=1024, intermediate_size=3072, head_dim=64, block_size=4096, dropout_rate=0.1, attn_dropout_rate=0.1, input_dim=1024, window_size=128, causal=True, channels_first=True, ) q_post = WindowLimitedTransformer( n_layer=8, n_head=16, dim=1024, intermediate_size=3072, head_dim=64, block_size=4096, dropout_rate=0.1, attn_dropout_rate=0.1, input_dim=1024, window_size=128, causal=True, channels_first=True, ) self.quantizer = DownsampleResidualVectorQuantize( input_dim=latent_dim, n_codebooks=n_codebooks, codebook_dim=codebook_dim, quantizer_dropout=0.5, codebook_size=codebook_size, semantic_codebook_size=semantic_codebook_size, downsample_factor=downsample_factor, pre_module=q_pre, post_module=q_post, ) # ---- Decoder ---- self.decoder = Decoder( input_channel=latent_dim, channels=decoder_dim, rates=decoder_rates, d_out=1, causal=True, n_transformer_layers=decoder_transformer_layers, ) self.apply(init_weights) self._autocast_dtype: tp.Optional[torch.dtype] = None # ---- Public API ---- @staticmethod def load(checkpoint_path: str, device: str = "cpu") -> "ECodec": """Load ECodec from a checkpoint file.""" model = ECodec() state_dict = torch.load(checkpoint_path, map_location=device, weights_only=True) # Drop causal_mask buffers from checkpoint (freed in WindowLimitedTransformer, saves ~288MB) state_dict = {k: v for k, v in state_dict.items() if not k.endswith("causal_mask")} model.load_state_dict(state_dict, strict=True) model.to(device) model.eval() return model def _remove_weight_norms(self) -> None: """Remove all weight norms for faster inference (no recomputation).""" for module in self.modules(): if isinstance(module, (CausalConvNet, CausalTransConvNet)): try: module.remove_weight_norm() except (ValueError, RuntimeError): pass # Old-style weight_norm on VQ conv layers (weight_g / weight_v) for module in self.modules(): if isinstance(module, nn.Conv1d) and hasattr(module, "weight_g"): torch.nn.utils.remove_weight_norm(module) def _encode_impl(self, audio: Tensor) -> tp.Tuple[Tensor, Tensor]: """Encode pipeline as single graph for torch.compile.""" z = self.encoder(audio) codes = self.quantizer.encode_only(z) return codes, z def _decode_impl(self, codes: Tensor) -> Tensor: """Decode pipeline as single graph for torch.compile.""" z = self.quantizer.decode(codes) return self.decoder(z) def optimize( self, dtype: torch.dtype = torch.float32, compile: bool = True, **compile_kwargs, ) -> "ECodec": """ Optimize for faster GPU inference with torch.compile and optional autocast. Parameters ---------- dtype : torch.dtype torch.float32 (default) for exact codes, or torch.bfloat16 for ~2x extra speedup with approximate codes (~60% codebook mismatch vs fp32 due to VQ sensitivity to small numerical differences). fp16 is NOT supported. compile : bool Apply torch.compile to encoder, decoder, and quantizer. **compile_kwargs Extra kwargs for torch.compile (e.g. mode="reduce-overhead"). """ if dtype == torch.float16: raise ValueError( "fp16 causes numerical instability in Snake activations and " "VQ distance computation. Use torch.bfloat16 instead." ) self._autocast_dtype = dtype if dtype != torch.float32 else None self._remove_weight_norms() if compile: self._encode_impl = torch.compile(self._encode_impl, **compile_kwargs) self._decode_impl = torch.compile(self._decode_impl, **compile_kwargs) return self def _autocast_ctx(self, ref: Tensor): """Return autocast context if enabled and on CUDA, else nullcontext.""" if self._autocast_dtype is not None and ref.is_cuda: return torch.autocast("cuda", dtype=self._autocast_dtype) return nullcontext() def _pad_audio(self, audio: Tensor) -> Tensor: """Pad audio to multiple of frame_length.""" length = audio.shape[-1] right_pad = math.ceil(length / self.frame_length) * self.frame_length - length if right_pad > 0: audio = F.pad(audio, (0, right_pad)) return audio @torch.inference_mode() def encode(self, audio: Tensor) -> tp.Tuple[Tensor, Tensor]: """ Encode audio waveform to discrete codes and continuous latent. Parameters ---------- audio : Tensor of shape (B, 1, T) Raw waveform at 44100 Hz. Returns ------- codes : Tensor of shape (B, 10, T') Discrete codebook indices. First row is semantic, rest are residual. continuous_z : Tensor of shape (B, 1024, T/512) Pre-quantization continuous latent from encoder. """ audio = self._pad_audio(audio) with self._autocast_ctx(audio): return self._encode_impl(audio) @torch.inference_mode() def decode(self, codes: Tensor) -> Tensor: """ Decode discrete codes back to audio. Parameters ---------- codes : Tensor of shape (B, 10, T') Discrete codebook indices. Returns ------- audio : Tensor of shape (B, 1, T) Reconstructed waveform. """ if codes.ndim == 2: codes = codes.unsqueeze(0) with self._autocast_ctx(codes): return self._decode_impl(codes) @torch.inference_mode() def encode_continuous(self, audio: Tensor) -> Tensor: """ Encode audio to continuous latent (after downsample + pre_module, before VQ). Parameters ---------- audio : Tensor of shape (B, 1, T) Returns ------- z : Tensor of shape (B, 1024, T/2048) Continuous latent at ~21.5 Hz (encoder 86Hz / quantizer downsample 4x). """ audio = self._pad_audio(audio) with self._autocast_ctx(audio): z = self.encoder(audio) # (B, 1024, T/512) at 86Hz z = self.quantizer.downsample(z) # (B, 1024, T/2048) at ~21.5Hz z = self.quantizer.pre_module(z) # transformer return z @torch.inference_mode() def decode_continuous(self, z: Tensor) -> Tensor: """ Decode from continuous latent (after pre_module, before VQ), bypassing VQ. Parameters ---------- z : Tensor of shape (B, 1024, T') Latent from encode_continuous. Returns ------- audio : Tensor of shape (B, 1, T) """ with self._autocast_ctx(z): z = self.quantizer.post_module(z) # transformer z = self.quantizer.upsample(z) # back to 86Hz return self.decoder(z) # --------------------------------------------------------------------------- # CLI test # --------------------------------------------------------------------------- if __name__ == "__main__": import os import sys ckpt_path = os.path.join(os.path.dirname(__file__), "codec.pth") if not os.path.exists(ckpt_path): print(f"Checkpoint not found at {ckpt_path}") sys.exit(1) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Loading ECodec on {device}...") codec = ECodec.load(ckpt_path, device=device) print(f"Loaded. Parameters: {sum(p.numel() for p in codec.parameters()):,}") if device == "cuda": codec.optimize() print("Optimized with bf16 + torch.compile") # Test encode/decode roundtrip x = torch.randn(1, 1, 44100, device=device) print(f"Input: {x.shape}") codes, z_cont = codec.encode(x) print(f"Codes: {codes.shape}, Continuous z: {z_cont.shape}") audio_out = codec.decode(codes) print(f"Decoded audio: {audio_out.shape}") z = codec.encode_continuous(x) print(f"Continuous encode: {z.shape}") audio_direct = codec.decode_continuous(z) print(f"Continuous decode: {audio_direct.shape}") print("All tests passed.")