ClionaOD commited on
Commit
98af51e
·
verified ·
1 Parent(s): 314904e

Add bad-bvd WavCoch tokenizer

Browse files
README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - audio
5
+ - wavcoch
6
+ - tokenizer
7
+ - neural-codec
8
+ ---
9
+
10
+ # WavCochCausalV64k-20ms-babyview
11
+
12
+ WavCoch causal **tokenizer** (8192-vocab FSQ) trained on the `bad` + `bvd` corpora. Quantizes
13
+ 16 kHz audio to FSQ code indices and decodes codes back to a cochleagram. This is the tokenizer
14
+ only — it does **not** render waveforms. Its codebook is distinct from
15
+ `TuKoResearch/WavCochCausalV8192`, so codes are **not** interchangeable.
16
+
17
+ - Trained checkpoint: `model_best.pt` (step 199000)
18
+
19
+ ```python
20
+ from transformers import AutoModel
21
+ import torch, torchaudio
22
+
23
+ m = AutoModel.from_pretrained("TuKoResearch/WavCochCausalV64k-20ms-babyview", trust_remote_code=True).eval()
24
+ wav, sr = torchaudio.load("clip.wav") # resample to 16 kHz first if needed
25
+ codes = m.quantize(wav.unsqueeze(0)) # [1, N] FSQ indices
26
+ coch = m.decode(codes) # [1, T, out_channels] cochleagram
27
+ ```
config.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "WavCoch"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_wavcoch.WavCochConfig",
7
+ "AutoModel": "modeling_wavcoch.WavCoch"
8
+ },
9
+ "causal_convs": true,
10
+ "causal_pad_mode": "repeat",
11
+ "channels": [
12
+ 8,
13
+ 8,
14
+ 8,
15
+ 5,
16
+ 5,
17
+ 5
18
+ ],
19
+ "decoder_block_type": "plain",
20
+ "decoder_dim": 512,
21
+ "decoder_kernel_size": 9,
22
+ "decoder_layers": 8,
23
+ "decoder_residual_bottleneck_factor": 4,
24
+ "decoder_residual_dilations": [
25
+ 1,
26
+ 3,
27
+ 9
28
+ ],
29
+ "decoder_residual_kernel_size": 7,
30
+ "dtype": "float32",
31
+ "encoder_block_type": "plain",
32
+ "encoder_dim": 512,
33
+ "encoder_kernel_size": 3,
34
+ "encoder_layers": 8,
35
+ "encoder_residual_bottleneck_factor": 4,
36
+ "encoder_residual_dilations": [
37
+ 1,
38
+ 3,
39
+ 9
40
+ ],
41
+ "encoder_residual_kernel_size": 7,
42
+ "has_vocoder": false,
43
+ "hop_length": 320,
44
+ "model_type": "wavcoch",
45
+ "out_channels": 211,
46
+ "quantizer": "FSQ",
47
+ "sample_rate": 16000,
48
+ "transformers_version": "5.10.2",
49
+ "vocab_size": 64000,
50
+ "vocoder_resblock": "1",
51
+ "vocoder_resblock_dilation_sizes": [
52
+ [
53
+ 1,
54
+ 3,
55
+ 5
56
+ ],
57
+ [
58
+ 1,
59
+ 3,
60
+ 5
61
+ ],
62
+ [
63
+ 1,
64
+ 3,
65
+ 5
66
+ ]
67
+ ],
68
+ "vocoder_resblock_kernel_sizes": [
69
+ 11,
70
+ 7,
71
+ 3
72
+ ],
73
+ "vocoder_upsample_initial_channel": 512,
74
+ "vocoder_upsample_kernel_sizes": [
75
+ 10,
76
+ 8,
77
+ 4,
78
+ 4
79
+ ],
80
+ "vocoder_upsample_rates": [
81
+ 5,
82
+ 4,
83
+ 2,
84
+ 2
85
+ ],
86
+ "window_padding": 1000,
87
+ "window_size": 1001
88
+ }
configuration_wavcoch.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WavCoch configuration for Hugging Face Transformers.
3
+ """
4
+
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class WavCochConfig(PretrainedConfig):
9
+ """Configuration class for WavCoch checkpoints with optional vocoder."""
10
+
11
+ model_type = "wavcoch"
12
+
13
+ def __init__(
14
+ self,
15
+ window_size: int = 1001,
16
+ window_padding: int = 1000,
17
+ hop_length: int = 80,
18
+ out_channels: int = 211,
19
+ causal_convs: bool = True,
20
+ causal_pad_mode: str = "repeat",
21
+ encoder_layers: int = 8,
22
+ encoder_dim: int = 512,
23
+ encoder_kernel_size: int = 3,
24
+ decoder_layers: int = 8,
25
+ decoder_dim: int = 512,
26
+ decoder_kernel_size: int = 9,
27
+ quantizer: str = "FSQ",
28
+ channels=None,
29
+ vocab_size: int = None,
30
+ sample_rate: int = 16000,
31
+ has_vocoder: bool = False,
32
+ vocoder_upsample_rates=None,
33
+ vocoder_upsample_kernel_sizes=None,
34
+ vocoder_upsample_initial_channel: int = 512,
35
+ vocoder_resblock: str = "1",
36
+ vocoder_resblock_kernel_sizes=None,
37
+ vocoder_resblock_dilation_sizes=None,
38
+ **kwargs,
39
+ ):
40
+ channels = list(channels or [8, 8, 8, 4, 4])
41
+ if vocab_size is None:
42
+ vocab_size = 1
43
+ for level in channels:
44
+ vocab_size *= int(level)
45
+
46
+ self.window_size = int(window_size)
47
+ self.window_padding = int(window_padding)
48
+ self.hop_length = int(hop_length)
49
+ self.out_channels = int(out_channels)
50
+ self.causal_convs = bool(causal_convs)
51
+ self.causal_pad_mode = str(causal_pad_mode)
52
+ self.encoder_layers = int(encoder_layers)
53
+ self.encoder_dim = int(encoder_dim)
54
+ self.encoder_kernel_size = int(encoder_kernel_size)
55
+ self.decoder_layers = int(decoder_layers)
56
+ self.decoder_dim = int(decoder_dim)
57
+ self.decoder_kernel_size = int(decoder_kernel_size)
58
+ self.quantizer = str(quantizer)
59
+ self.channels = channels
60
+ self.vocab_size = int(vocab_size)
61
+ self.sample_rate = int(sample_rate)
62
+
63
+ self.has_vocoder = bool(has_vocoder)
64
+ self.vocoder_upsample_rates = list(vocoder_upsample_rates or [5, 4, 2, 2])
65
+ self.vocoder_upsample_kernel_sizes = list(vocoder_upsample_kernel_sizes or [10, 8, 4, 4])
66
+ self.vocoder_upsample_initial_channel = int(vocoder_upsample_initial_channel)
67
+ self.vocoder_resblock = str(vocoder_resblock)
68
+ self.vocoder_resblock_kernel_sizes = list(vocoder_resblock_kernel_sizes or [11, 7, 3])
69
+ self.vocoder_resblock_dilation_sizes = [
70
+ list(d) for d in (vocoder_resblock_dilation_sizes or [[1, 3, 5], [1, 3, 5], [1, 3, 5]])
71
+ ]
72
+
73
+ super().__init__(**kwargs)
configure_wavcoch.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Backward-compatible import shim for older WavCoch repos.
3
+ """
4
+
5
+ from .configuration_wavcoch import WavCochConfig
6
+
7
+
8
+ __all__ = ["WavCochConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f69a4bbe2cd938df02f97e3b82de1e901d291035887566953f95d464ceadd464
3
+ size 44276180
modeling_wavcoch.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WavCoch model for Hugging Face Transformers.
3
+
4
+ This implementation is self-contained so HF-hosted WavCoch checkpoints do not
5
+ depend on the local auristream package or vector_quantize_pytorch.
6
+ """
7
+
8
+ import math
9
+ import os
10
+ from typing import List, Optional
11
+
12
+ os.environ.setdefault("USE_TORCH_XLA", "0")
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ from torch.nn import Conv1d, ConvTranspose1d
18
+ from torch.nn.utils import remove_weight_norm
19
+ try:
20
+ from torch.nn.utils.parametrizations import weight_norm
21
+ except ImportError: # pragma: no cover - older PyTorch compatibility
22
+ from torch.nn.utils import weight_norm
23
+
24
+ from transformers import PreTrainedModel
25
+ from transformers.modeling_outputs import BaseModelOutput
26
+ try:
27
+ from transformers.tokenization_utils_base import BatchEncoding
28
+ except ImportError: # pragma: no cover - compatibility with older Transformers
29
+ from transformers.tokenization_utils import BatchEncoding
30
+ import transformers.modeling_utils as transformers_modeling_utils
31
+ import transformers.utils.import_utils as transformers_import_utils
32
+
33
+ transformers_import_utils.is_torch_xla_available = lambda *args, **kwargs: False
34
+ transformers_modeling_utils.is_torch_xla_available = lambda *args, **kwargs: False
35
+
36
+ try:
37
+ from .configuration_wavcoch import WavCochConfig
38
+ except ImportError: # pragma: no cover - compatibility with older repos
39
+ from .configure_wavcoch import WavCochConfig
40
+
41
+
42
+ class CausalConv1d(nn.Module):
43
+ """1D causal convolution with left-only padding."""
44
+
45
+ def __init__(
46
+ self,
47
+ in_channels: int,
48
+ out_channels: int,
49
+ kernel_size: int,
50
+ stride: int = 1,
51
+ dilation: int = 1,
52
+ bias: bool = True,
53
+ groups: int = 1,
54
+ pad_mode: str = "repeat",
55
+ constant_value: float = 0.0,
56
+ ):
57
+ super().__init__()
58
+ left_pad = dilation * (kernel_size - 1)
59
+ if pad_mode == "repeat":
60
+ self.pad = nn.ReplicationPad1d((left_pad, 0))
61
+ elif pad_mode == "constant":
62
+ self.pad = nn.ConstantPad1d((left_pad, 0), constant_value)
63
+ else:
64
+ raise ValueError(f"Unsupported pad_mode: {pad_mode}")
65
+ self.conv = nn.Conv1d(
66
+ in_channels,
67
+ out_channels,
68
+ kernel_size=kernel_size,
69
+ stride=stride,
70
+ padding=0,
71
+ dilation=dilation,
72
+ groups=groups,
73
+ bias=bias,
74
+ )
75
+
76
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
77
+ return self.conv(self.pad(x))
78
+
79
+
80
+ def _build_conv1d(
81
+ in_channels: int,
82
+ out_channels: int,
83
+ kernel_size: int,
84
+ *,
85
+ causal: bool,
86
+ dilation: int = 1,
87
+ pad_mode: str = "repeat",
88
+ ):
89
+ if causal:
90
+ return CausalConv1d(
91
+ in_channels,
92
+ out_channels,
93
+ kernel_size=kernel_size,
94
+ stride=1,
95
+ dilation=dilation,
96
+ pad_mode=pad_mode,
97
+ )
98
+
99
+ padding = dilation * (kernel_size - 1) // 2
100
+ return nn.Conv1d(
101
+ in_channels,
102
+ out_channels,
103
+ kernel_size=kernel_size,
104
+ stride=1,
105
+ dilation=dilation,
106
+ padding=padding,
107
+ )
108
+
109
+
110
+ class FSQ(nn.Module):
111
+ """Finite Scalar Quantization with the subset of functionality needed for inference."""
112
+
113
+ def __init__(self, levels: List[int], dim: int):
114
+ super().__init__()
115
+ if not levels:
116
+ raise ValueError("FSQ levels must be non-empty")
117
+
118
+ self.levels = [int(level) for level in levels]
119
+ self.codebook_dim = len(self.levels)
120
+ self.dim = int(dim)
121
+
122
+ level_tensor = torch.tensor(self.levels, dtype=torch.int32)
123
+ basis = torch.cumprod(torch.tensor([1] + self.levels[:-1], dtype=torch.int32), dim=0)
124
+ self.register_buffer("_levels", level_tensor, persistent=False)
125
+ self.register_buffer("_basis", basis, persistent=False)
126
+
127
+ if self.dim != self.codebook_dim:
128
+ self.project_in = nn.Linear(self.dim, self.codebook_dim)
129
+ self.project_out = nn.Linear(self.codebook_dim, self.dim)
130
+ else:
131
+ self.project_in = nn.Identity()
132
+ self.project_out = nn.Identity()
133
+
134
+ def _refresh_level_buffers(self, device: Optional[torch.device] = None):
135
+ level_values = [int(level) for level in self.levels]
136
+ if device is None:
137
+ if isinstance(self.project_in, nn.Linear):
138
+ device = self.project_in.weight.device
139
+ elif isinstance(self.project_out, nn.Linear):
140
+ device = self.project_out.weight.device
141
+ else:
142
+ device = self._levels.device
143
+
144
+ self._levels = torch.tensor(level_values, dtype=torch.int32, device=device)
145
+ self._basis = torch.cumprod(
146
+ torch.tensor([1] + level_values[:-1], dtype=torch.int32, device=device),
147
+ dim=0,
148
+ )
149
+
150
+ def bound(self, z: torch.Tensor, eps: float = 1e-3) -> torch.Tensor:
151
+ levels = self._levels.to(dtype=z.dtype, device=z.device)
152
+ half_l = (levels - 1) * (1 + eps) / 2
153
+ offset = torch.where(
154
+ (self._levels % 2).to(device=z.device) == 0,
155
+ torch.tensor(0.5, device=z.device, dtype=z.dtype),
156
+ torch.tensor(0.0, device=z.device, dtype=z.dtype),
157
+ )
158
+ shift = (offset / half_l).atanh()
159
+ return (z + shift).tanh() * half_l - offset
160
+
161
+ def _scale_and_shift(self, zhat_normalized: torch.Tensor) -> torch.Tensor:
162
+ half_width = (self._levels // 2).to(dtype=zhat_normalized.dtype, device=zhat_normalized.device)
163
+ return (zhat_normalized * half_width) + half_width
164
+
165
+ def _scale_and_shift_inverse(self, zhat: torch.Tensor) -> torch.Tensor:
166
+ half_width = (self._levels // 2).to(dtype=zhat.dtype, device=zhat.device)
167
+ return (zhat - half_width) / half_width
168
+
169
+ def quantize_values(self, z: torch.Tensor) -> torch.Tensor:
170
+ self._refresh_level_buffers(device=z.device)
171
+ half_width = (self._levels // 2).to(dtype=z.dtype, device=z.device)
172
+ return self.bound(z).round() / half_width
173
+
174
+ def codes_to_indices(self, zhat: torch.Tensor) -> torch.Tensor:
175
+ self._refresh_level_buffers(device=zhat.device)
176
+ zhat = self._scale_and_shift(zhat)
177
+ basis = self._basis.to(device=zhat.device, dtype=zhat.dtype)
178
+ return (zhat * basis).sum(dim=-1).to(torch.int32)
179
+
180
+ def indices_to_level_indices(self, indices: torch.Tensor) -> torch.Tensor:
181
+ self._refresh_level_buffers(device=indices.device)
182
+ indices = indices.unsqueeze(-1)
183
+ levels = self._levels.to(device=indices.device)
184
+ basis = self._basis.to(device=indices.device)
185
+ return (indices // basis) % levels
186
+
187
+ def indices_to_codes(self, indices: torch.Tensor) -> torch.Tensor:
188
+ self._refresh_level_buffers(device=indices.device)
189
+ level_indices = self.indices_to_level_indices(indices)
190
+ codes = self._scale_and_shift_inverse(level_indices.to(dtype=torch.float32))
191
+ return self.project_out(codes)
192
+
193
+ def forward(self, z: torch.Tensor):
194
+ orig_dtype = z.dtype
195
+ z = self.project_in(z.to(torch.float32))
196
+ q = self.quantize_values(z)
197
+ indices = self.codes_to_indices(q)
198
+ out = self.project_out(q).to(orig_dtype)
199
+ return out, indices.long()
200
+
201
+
202
+ LRELU_SLOPE = 0.1
203
+
204
+
205
+ def get_padding(kernel_size: int, dilation: int = 1) -> int:
206
+ return int((kernel_size * dilation - dilation) / 2)
207
+
208
+
209
+ def init_weights(module, mean: float = 0.0, std: float = 0.01):
210
+ classname = module.__class__.__name__
211
+ if classname.find("Conv") != -1 and hasattr(module, "weight"):
212
+ module.weight.data.normal_(mean, std)
213
+
214
+
215
+ class ResBlock1(nn.Module):
216
+ __constants__ = ["lrelu_slope"]
217
+
218
+ def __init__(self, channels: int, kernel_size: int = 3, dilation=(1, 3, 5)):
219
+ super().__init__()
220
+ self.lrelu_slope = LRELU_SLOPE
221
+
222
+ ch = channels
223
+ ks = kernel_size
224
+ self.convs1 = nn.Sequential(
225
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[0]), dilation[0])),
226
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[1]), dilation[1])),
227
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, dilation[2]), dilation[2])),
228
+ )
229
+ self.convs2 = nn.Sequential(
230
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
231
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
232
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(ks, 1))),
233
+ )
234
+ self.convs1.apply(init_weights)
235
+ self.convs2.apply(init_weights)
236
+
237
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
238
+ for conv1, conv2 in zip(self.convs1, self.convs2):
239
+ xt = F.leaky_relu(x, self.lrelu_slope)
240
+ xt = conv1(xt)
241
+ xt = F.leaky_relu(xt, self.lrelu_slope)
242
+ xt = conv2(xt)
243
+ x = xt + x
244
+ return x
245
+
246
+ def remove_weight_norm(self):
247
+ for layer in self.convs1:
248
+ remove_weight_norm(layer)
249
+ for layer in self.convs2:
250
+ remove_weight_norm(layer)
251
+
252
+
253
+ class ResBlock2(nn.Module):
254
+ __constants__ = ["lrelu_slope"]
255
+
256
+ def __init__(self, channels: int, kernel_size: int = 3, dilation=(1, 3)):
257
+ super().__init__()
258
+ self.lrelu_slope = LRELU_SLOPE
259
+
260
+ ch = channels
261
+ ks = kernel_size
262
+ self.convs = nn.ModuleList(
263
+ [
264
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(kernel_size, dilation[0]), dilation[0])),
265
+ weight_norm(Conv1d(ch, ch, ks, 1, get_padding(kernel_size, dilation[1]), dilation[1])),
266
+ ]
267
+ )
268
+ self.convs.apply(init_weights)
269
+
270
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
271
+ for conv in self.convs:
272
+ xt = F.leaky_relu(x, self.lrelu_slope)
273
+ xt = conv(xt)
274
+ x = xt + x
275
+ return x
276
+
277
+ def remove_weight_norm(self):
278
+ for layer in self.convs:
279
+ remove_weight_norm(layer)
280
+
281
+
282
+ class Generator(nn.Module):
283
+ __constants__ = ["lrelu_slope", "num_kernels", "num_upsamples"]
284
+
285
+ def __init__(
286
+ self,
287
+ out_channels: int = 211,
288
+ upsample_rates=None,
289
+ upsample_kernel_sizes=None,
290
+ upsample_initial_channel: int = 512,
291
+ resblock: str = "1",
292
+ resblock_kernel_sizes=None,
293
+ resblock_dilation_sizes=None,
294
+ ):
295
+ super().__init__()
296
+ upsample_rates = list(upsample_rates or [5, 4, 2, 2])
297
+ upsample_kernel_sizes = list(upsample_kernel_sizes or [10, 8, 4, 4])
298
+ resblock_kernel_sizes = list(resblock_kernel_sizes or [11, 7, 3])
299
+ resblock_dilation_sizes = [list(d) for d in (resblock_dilation_sizes or [[1, 3, 5], [1, 3, 5], [1, 3, 5]])]
300
+
301
+ self.num_kernels = len(resblock_kernel_sizes)
302
+ self.num_upsamples = len(upsample_rates)
303
+ self.lrelu_slope = LRELU_SLOPE
304
+
305
+ self.conv_pre = weight_norm(Conv1d(out_channels, upsample_initial_channel, 7, 1, padding=3))
306
+ resblock_cls = ResBlock1 if resblock == "1" else ResBlock2
307
+
308
+ ups = []
309
+ for i, (rate, kernel) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
310
+ ups.append(
311
+ weight_norm(
312
+ ConvTranspose1d(
313
+ upsample_initial_channel // (2 ** i),
314
+ upsample_initial_channel // (2 ** (i + 1)),
315
+ kernel,
316
+ rate,
317
+ padding=(kernel - rate) // 2,
318
+ )
319
+ )
320
+ )
321
+ self.ups = nn.Sequential(*ups)
322
+
323
+ resblocks = []
324
+ for i in range(len(self.ups)):
325
+ ch = upsample_initial_channel // (2 ** (i + 1))
326
+ resblocks.append(
327
+ nn.Sequential(
328
+ *[
329
+ resblock_cls(ch, kernel, dilation)
330
+ for kernel, dilation in zip(resblock_kernel_sizes, resblock_dilation_sizes)
331
+ ]
332
+ )
333
+ )
334
+ self.resblocks = nn.Sequential(*resblocks)
335
+
336
+ self.conv_post = weight_norm(Conv1d(ch, 1, 17, 1, padding=0))
337
+ self.ups.apply(init_weights)
338
+ self.conv_post.apply(init_weights)
339
+
340
+ def load_state_dict(self, state_dict, strict: bool = True):
341
+ new_state_dict = {}
342
+ for key, value in state_dict.items():
343
+ new_key = key
344
+ if "resblocks" in key:
345
+ parts = key.split(".")
346
+ if len(parts) == 5:
347
+ layer = int(parts[1])
348
+ new_key = f"resblocks.{layer // 3}.{layer % 3}.{'.'.join(parts[2:])}"
349
+ new_state_dict[new_key] = value
350
+
351
+ current_state = self.state_dict()
352
+ for key, value in list(new_state_dict.items()):
353
+ if key not in current_state:
354
+ continue
355
+ len_diff = value.dim() - current_state[key].dim()
356
+ if len_diff == -1:
357
+ new_state_dict[key] = value.unsqueeze(-1)
358
+ elif len_diff == 1:
359
+ new_state_dict[key] = value.squeeze(-1)
360
+
361
+ super().load_state_dict(new_state_dict, strict=strict)
362
+
363
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
364
+ x = self.conv_pre(x.permute(0, 2, 1))
365
+
366
+ for upsample_layer, resblock_group in zip(self.ups, self.resblocks):
367
+ x = F.leaky_relu(x, self.lrelu_slope)
368
+ x = upsample_layer(x)
369
+ xs = 0
370
+ for resblock in resblock_group:
371
+ xs = xs + resblock(x)
372
+ x = xs / self.num_kernels
373
+
374
+ x = F.leaky_relu(x)
375
+ x = self.conv_post(x)
376
+ return torch.tanh(x)
377
+
378
+ def remove_weight_norm(self):
379
+ for layer in self.ups:
380
+ remove_weight_norm(layer)
381
+ for group in self.resblocks:
382
+ for block in group:
383
+ block.remove_weight_norm()
384
+ remove_weight_norm(self.conv_pre)
385
+ remove_weight_norm(self.conv_post)
386
+
387
+
388
+ class WavCoch(PreTrainedModel):
389
+ """Causal waveform-to-cochleagram tokenizer with optional vocoder."""
390
+
391
+ config_class = WavCochConfig
392
+ main_input_name = "wav"
393
+
394
+ def __init__(self, config: WavCochConfig):
395
+ super().__init__(config)
396
+ self.config = config
397
+
398
+ self.N = int(config.window_size)
399
+ self.hop_length = int(config.hop_length)
400
+ self.window_padding = int(getattr(config, "window_padding", self.N - self.hop_length))
401
+ self.causal_convs = bool(getattr(config, "causal_convs", True))
402
+ self.causal_pad_mode = getattr(config, "causal_pad_mode", "repeat")
403
+
404
+ out_bins = self.N // 2 + 1
405
+ self.conv_real_filters = nn.Conv1d(1, out_bins, kernel_size=self.N, stride=self.hop_length)
406
+ self.conv_imag_filters = nn.Conv1d(1, out_bins, kernel_size=self.N, stride=self.hop_length)
407
+ self._initialize_conv_filters()
408
+
409
+ self.encoder = self._build_conv_stack(
410
+ in_channels=out_bins,
411
+ out_channels=config.encoder_dim,
412
+ num_layers=config.encoder_layers,
413
+ kernel_size=config.encoder_kernel_size,
414
+ causal=self.causal_convs,
415
+ )
416
+ self.quantizer = FSQ(levels=list(config.channels), dim=config.encoder_dim)
417
+ self.decoder = self._build_conv_stack(
418
+ in_channels=config.decoder_dim,
419
+ out_channels=config.out_channels,
420
+ num_layers=config.decoder_layers,
421
+ kernel_size=config.decoder_kernel_size,
422
+ causal=self.causal_convs,
423
+ )
424
+
425
+ self.has_vocoder = bool(getattr(config, "has_vocoder", False))
426
+ if self.has_vocoder:
427
+ if int(config.out_channels) != 211:
428
+ raise ValueError("Bundled vocoder currently expects 211 cochleagram channels")
429
+ self.vocoder = Generator(
430
+ out_channels=config.out_channels,
431
+ upsample_rates=config.vocoder_upsample_rates,
432
+ upsample_kernel_sizes=config.vocoder_upsample_kernel_sizes,
433
+ upsample_initial_channel=config.vocoder_upsample_initial_channel,
434
+ resblock=config.vocoder_resblock,
435
+ resblock_kernel_sizes=config.vocoder_resblock_kernel_sizes,
436
+ resblock_dilation_sizes=config.vocoder_resblock_dilation_sizes,
437
+ )
438
+ else:
439
+ self.vocoder = None
440
+
441
+ self._vocab_size = int(config.vocab_size)
442
+ self.post_init()
443
+
444
+ def _build_conv_stack(
445
+ self,
446
+ in_channels: int,
447
+ out_channels: int,
448
+ num_layers: int,
449
+ kernel_size: int,
450
+ causal: bool,
451
+ ) -> nn.Sequential:
452
+ layers = []
453
+ for layer_idx in range(int(num_layers)):
454
+ input_channels = in_channels if layer_idx == 0 else out_channels
455
+ conv = _build_conv1d(
456
+ input_channels,
457
+ out_channels,
458
+ kernel_size,
459
+ causal=causal,
460
+ pad_mode=self.causal_pad_mode,
461
+ )
462
+ layers.extend([conv, nn.ReLU()])
463
+ return nn.Sequential(*layers)
464
+
465
+ def _compute_twiddle_factors(self):
466
+ n = torch.arange(self.N, dtype=torch.float32).unsqueeze(1)
467
+ k = torch.arange(self.N, dtype=torch.float32).unsqueeze(0)
468
+ angles = -2.0 * math.pi * n * k / float(self.N)
469
+ return torch.cos(angles), torch.sin(angles)
470
+
471
+ def _initialize_conv_filters(self):
472
+ with torch.no_grad():
473
+ cos_matrix, sin_matrix = self._compute_twiddle_factors()
474
+ cos_matrix = cos_matrix[: self.N // 2 + 1, :]
475
+ sin_matrix = sin_matrix[: self.N // 2 + 1, :]
476
+ window = torch.hann_window(self.N, periodic=True).view(1, 1, -1)
477
+ real_weights = (cos_matrix.unsqueeze(1) * window).to(dtype=self.conv_real_filters.weight.dtype)
478
+ imag_weights = (sin_matrix.unsqueeze(1) * window).to(dtype=self.conv_imag_filters.weight.dtype)
479
+ self.conv_real_filters.weight.copy_(real_weights)
480
+ self.conv_imag_filters.weight.copy_(imag_weights)
481
+
482
+ for param in self.conv_real_filters.parameters():
483
+ param.requires_grad_(False)
484
+ for param in self.conv_imag_filters.parameters():
485
+ param.requires_grad_(False)
486
+
487
+ def _normalize_sample_rate(self, sample_rate: Optional[int], sampling_rate: Optional[int]) -> int:
488
+ if sample_rate is not None and sampling_rate is not None and sample_rate != sampling_rate:
489
+ raise ValueError(f"sample_rate ({sample_rate}) and sampling_rate ({sampling_rate}) conflict")
490
+ resolved = int(sample_rate or sampling_rate or self.config.sample_rate)
491
+ if resolved != int(self.config.sample_rate):
492
+ raise ValueError(
493
+ f"WavCoch expects {self.config.sample_rate} Hz audio, but received {resolved} Hz"
494
+ )
495
+ return resolved
496
+
497
+ def _prepare_wav_batch(self, wav) -> torch.Tensor:
498
+ if isinstance(wav, list):
499
+ wav = [item if isinstance(item, torch.Tensor) else torch.tensor(item) for item in wav]
500
+ normalized = []
501
+ for item in wav:
502
+ if item.ndim == 1:
503
+ normalized.append(item)
504
+ elif item.ndim == 2 and 1 in item.shape:
505
+ normalized.append(item.reshape(-1))
506
+ else:
507
+ raise ValueError(f"Unexpected list element shape {tuple(item.shape)}")
508
+ wav = torch.nn.utils.rnn.pad_sequence(normalized, batch_first=True).unsqueeze(1)
509
+ elif isinstance(wav, torch.Tensor):
510
+ if wav.ndim == 1:
511
+ wav = wav.unsqueeze(0).unsqueeze(0)
512
+ elif wav.ndim == 2:
513
+ wav = wav.unsqueeze(1)
514
+ elif wav.ndim != 3:
515
+ raise ValueError(f"Unexpected tensor shape {tuple(wav.shape)}, expected 1D, 2D or 3D")
516
+ else:
517
+ raise TypeError(f"Unsupported input type: {type(wav)}")
518
+
519
+ return wav.to(dtype=torch.float32)
520
+
521
+ @property
522
+ def vocab_size(self) -> int:
523
+ return self._vocab_size
524
+
525
+ def _resolve_wav_input(
526
+ self,
527
+ wav: Optional[torch.Tensor],
528
+ input_values: Optional[torch.Tensor],
529
+ ) -> torch.Tensor:
530
+ if wav is not None and input_values is not None:
531
+ raise ValueError("Provide either `wav` or `input_values`, not both")
532
+ resolved = wav if wav is not None else input_values
533
+ if resolved is None:
534
+ raise ValueError("WavCoch requires waveform input via `wav` or `input_values`")
535
+ return resolved
536
+
537
+ def _encode_quantized(
538
+ self,
539
+ wav: torch.Tensor,
540
+ pad: bool = True,
541
+ ):
542
+ wav = self._prepare_wav_batch(wav)
543
+ if pad:
544
+ wav = F.pad(wav, (self.window_padding, 0), mode="constant", value=0.0)
545
+
546
+ with torch.no_grad():
547
+ real_part = self.conv_real_filters(wav)
548
+ imag_part = self.conv_imag_filters(wav)
549
+
550
+ x = real_part + imag_part
551
+ x = self.encoder(x).permute(0, 2, 1)
552
+ quantized, indices = self.quantizer(x)
553
+ return quantized, indices
554
+
555
+ def forward(
556
+ self,
557
+ wav: Optional[torch.Tensor] = None,
558
+ coch: Optional[torch.Tensor] = None,
559
+ return_tensors: str = "pt",
560
+ sample_rate: Optional[int] = None,
561
+ sampling_rate: Optional[int] = None,
562
+ pad: bool = True,
563
+ output_hidden_states: Optional[bool] = False,
564
+ return_dict: Optional[bool] = True,
565
+ input_values: Optional[torch.Tensor] = None,
566
+ ):
567
+ del return_tensors # unused, kept for tokenizer-like API compatibility
568
+ self._normalize_sample_rate(sample_rate, sampling_rate)
569
+ wav = self._resolve_wav_input(wav, input_values)
570
+ quantized, indices = self._encode_quantized(wav, pad=pad)
571
+
572
+ if output_hidden_states:
573
+ hidden_states = (quantized,)
574
+ if not return_dict:
575
+ return quantized, hidden_states
576
+ return BaseModelOutput(last_hidden_state=quantized, hidden_states=hidden_states)
577
+
578
+ if coch is None:
579
+ codes = indices.long()
580
+ return BatchEncoding({"input_values": codes, "input_ids": codes})
581
+
582
+ pred_coch = self.decoder(quantized.permute(0, 2, 1)).permute(0, 2, 1)
583
+ loss = F.l1_loss(pred_coch, coch)
584
+ return pred_coch, loss, None
585
+
586
+ @torch.no_grad()
587
+ def quantize(self, wav: torch.Tensor, pad: bool = True) -> torch.Tensor:
588
+ _, indices = self._encode_quantized(wav, pad=pad)
589
+ return indices.long()
590
+
591
+ @torch.no_grad()
592
+ def decode(self, indices: torch.Tensor) -> torch.Tensor:
593
+ if indices.ndim == 1:
594
+ indices = indices.unsqueeze(0)
595
+ emb = self.quantizer.indices_to_codes(indices.long())
596
+ return self.decoder(emb.permute(0, 2, 1)).permute(0, 2, 1)
597
+
598
+ @torch.no_grad()
599
+ def wav2coch(self, wav: torch.Tensor, pad: bool = True) -> torch.Tensor:
600
+ quantized, _ = self._encode_quantized(wav, pad=pad)
601
+ return self.decoder(quantized.permute(0, 2, 1)).permute(0, 2, 1)
602
+
603
+ @torch.no_grad()
604
+ def vocode(self, coch: torch.Tensor) -> torch.Tensor:
605
+ if self.vocoder is None:
606
+ raise ValueError("This WavCoch checkpoint does not include a bundled vocoder")
607
+
608
+ if coch.ndim == 2:
609
+ coch = coch.unsqueeze(0)
610
+ elif coch.ndim != 3:
611
+ raise ValueError(f"Unexpected cochleagram shape {tuple(coch.shape)}")
612
+
613
+ if coch.shape[-1] != self.config.out_channels and coch.shape[1] == self.config.out_channels:
614
+ coch = coch.transpose(1, 2)
615
+
616
+ return self.vocoder(coch)
617
+
618
+ @torch.no_grad()
619
+ def decode_audio(self, indices: torch.Tensor) -> torch.Tensor:
620
+ return self.vocode(self.decode(indices))