File size: 42,306 Bytes
0981df7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 | """
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.")
|