Prompt48 commited on
Commit
91b39fb
·
verified ·
1 Parent(s): c176142

Upload edit\Qwen3-TTS-test\qwen_tts\core\tokenizer_12hz\modeling_qwen3_tts_tokenizer_v2.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//qwen_tts//core//tokenizer_12hz//modeling_qwen3_tts_tokenizer_v2.py ADDED
@@ -0,0 +1,1027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Qwen3TTSTokenizerV2 model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Callable, Optional, Union, List
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch import nn
24
+ from torch.nn import Parameter
25
+ from torch.nn import functional as F
26
+ from transformers import MimiConfig, MimiModel
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache
29
+ from transformers.integrations import use_kernel_forward_from_hub
30
+ from transformers.masking_utils import (
31
+ create_causal_mask,
32
+ create_sliding_window_causal_mask,
33
+ )
34
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
35
+ from transformers.modeling_layers import GradientCheckpointingLayer
36
+ from transformers.modeling_outputs import BaseModelOutputWithPast
37
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
38
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from transformers.processing_utils import Unpack
40
+ from transformers.utils import ModelOutput, auto_docstring, logging
41
+ from transformers.utils.deprecation import deprecate_kwarg
42
+ from transformers.utils.generic import check_model_inputs
43
+
44
+ from .configuration_qwen3_tts_tokenizer_v2 import (
45
+ Qwen3TTSTokenizerV2Config,
46
+ Qwen3TTSTokenizerV2DecoderConfig,
47
+ )
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ @dataclass
53
+ @auto_docstring
54
+ class Qwen3TTSTokenizerV2EncoderOutput(ModelOutput):
55
+ r"""
56
+ audio_codes (`List[torch.LongTensor]`):
57
+ Discret code embeddings computed using `model.encode`, each tensor has shape (codes_length_i, num_quantizers).
58
+ """
59
+
60
+ audio_codes: List[torch.LongTensor] = None
61
+
62
+
63
+ @dataclass
64
+ @auto_docstring
65
+ class Qwen3TTSTokenizerV2DecoderOutput(ModelOutput):
66
+ r"""
67
+ audio_values (`List[torch.FloatTensor]`):
68
+ Decoded audio values, obtained using the decoder part of Qwen3TTSTokenizerV1.
69
+ Each tensor has shape (segment_length_i).
70
+ """
71
+
72
+ audio_values: List[torch.FloatTensor] = None
73
+
74
+
75
+ def rotate_half(x):
76
+ """Rotates half the hidden dims of the input."""
77
+ x1 = x[..., : x.shape[-1] // 2]
78
+ x2 = x[..., x.shape[-1] // 2 :]
79
+ return torch.cat((-x2, x1), dim=-1)
80
+
81
+
82
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
83
+ """Applies Rotary Position Embedding to the query and key tensors.
84
+
85
+ Args:
86
+ q (`torch.Tensor`): The query tensor.
87
+ k (`torch.Tensor`): The key tensor.
88
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
89
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
90
+ position_ids (`torch.Tensor`, *optional*):
91
+ Deprecated and unused.
92
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
93
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
94
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
95
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
96
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
97
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
98
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
99
+ Returns:
100
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
101
+ """
102
+ cos = cos.unsqueeze(unsqueeze_dim)
103
+ sin = sin.unsqueeze(unsqueeze_dim)
104
+ q_embed = (q * cos) + (rotate_half(q) * sin)
105
+ k_embed = (k * cos) + (rotate_half(k) * sin)
106
+ return q_embed, k_embed
107
+
108
+
109
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
110
+ """
111
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
112
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
113
+ """
114
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
115
+ if n_rep == 1:
116
+ return hidden_states
117
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
118
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
119
+
120
+
121
+ def eager_attention_forward(
122
+ module: nn.Module,
123
+ query: torch.Tensor,
124
+ key: torch.Tensor,
125
+ value: torch.Tensor,
126
+ attention_mask: Optional[torch.Tensor],
127
+ scaling: float,
128
+ dropout: float = 0.0,
129
+ **kwargs,
130
+ ):
131
+ key_states = repeat_kv(key, module.num_key_value_groups)
132
+ value_states = repeat_kv(value, module.num_key_value_groups)
133
+
134
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
135
+ if attention_mask is not None:
136
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
137
+ attn_weights = attn_weights + causal_mask
138
+
139
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
140
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
141
+ attn_output = torch.matmul(attn_weights, value_states)
142
+ attn_output = attn_output.transpose(1, 2).contiguous()
143
+
144
+ return attn_output, attn_weights
145
+
146
+
147
+ @auto_docstring
148
+ class Qwen3TTSTokenizerV2DecoderPreTrainedModel(PreTrainedModel):
149
+ config: Qwen3TTSTokenizerV2DecoderConfig
150
+ base_model_prefix = "model"
151
+ supports_gradient_checkpointing = True
152
+ _skip_keys_device_placement = "past_key_values"
153
+ _supports_flash_attn = True
154
+ _supports_sdpa = True
155
+ _can_compile_fullgraph = False
156
+ _supports_attention_backend = True
157
+
158
+
159
+ class Qwen3TTSTokenizerV2CausalConvNet(nn.Module):
160
+ def __init__(
161
+ self,
162
+ in_channels,
163
+ out_channels,
164
+ kernel_size,
165
+ dilation=1,
166
+ stride=1,
167
+ groups=1,
168
+ ):
169
+ super().__init__()
170
+ self.conv = nn.Conv1d(
171
+ in_channels,
172
+ out_channels,
173
+ kernel_size,
174
+ stride=stride,
175
+ dilation=dilation,
176
+ groups=groups,
177
+ )
178
+ self.stride = stride
179
+ self.kernel_size = (kernel_size - 1) * dilation + 1
180
+ self.dilation = dilation
181
+ self.padding = self.kernel_size - self.stride
182
+
183
+ def _get_extra_padding_for_conv1d(self, hidden_state: torch.Tensor) -> int:
184
+ length = hidden_state.shape[-1]
185
+ n_frames = (length - self.kernel_size + self.padding) / self.stride + 1
186
+ ideal_length = (math.ceil(n_frames) - 1) * self.stride + (self.kernel_size - self.padding)
187
+ return ideal_length - length
188
+
189
+ def forward(self, hidden_state):
190
+ extra_padding = self._get_extra_padding_for_conv1d(hidden_state)
191
+ hidden_state = F.pad(hidden_state, (self.padding, extra_padding), mode="constant", value=0)
192
+ return self.conv(hidden_state).contiguous()
193
+
194
+
195
+ class Qwen3TTSTokenizerV2CausalTransConvNet(nn.Module):
196
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1):
197
+ super().__init__()
198
+ self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride)
199
+
200
+ pad = kernel_size - stride
201
+ self.left_pad = 0
202
+ self.right_pad = int(pad)
203
+
204
+ def forward(self, hidden_state):
205
+ hidden_state = self.conv(hidden_state)
206
+ if self.right_pad > 0:
207
+ hidden_state = hidden_state[..., : hidden_state.shape[-1] - self.right_pad]
208
+ return hidden_state.contiguous()
209
+
210
+
211
+ class Qwen3TTSTokenizerV2ConvNeXtBlock(nn.Module):
212
+ def __init__(self, dim: int):
213
+ super().__init__()
214
+ self.dwconv = Qwen3TTSTokenizerV2CausalConvNet(
215
+ dim,
216
+ dim,
217
+ kernel_size=7,
218
+ groups=dim,
219
+ dilation=1,
220
+ )
221
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
222
+ self.pwconv1 = nn.Linear(dim, 4 * dim)
223
+ self.act = nn.GELU()
224
+ self.pwconv2 = nn.Linear(4 * dim, dim)
225
+ self.gamma = nn.Parameter(1e-6 * torch.ones(dim))
226
+
227
+ def forward(self, hidden_states):
228
+ input = hidden_states
229
+
230
+ hidden_states = self.dwconv(hidden_states)
231
+ hidden_states = hidden_states.permute(0, 2, 1)
232
+ hidden_states = self.norm(hidden_states)
233
+ hidden_states = self.pwconv1(hidden_states)
234
+ hidden_states = self.act(hidden_states)
235
+ hidden_states = self.pwconv2(hidden_states)
236
+
237
+ hidden_states = self.gamma * hidden_states
238
+
239
+ hidden_states = hidden_states.permute(0, 2, 1)
240
+
241
+ hidden_states = input + hidden_states
242
+
243
+ return hidden_states
244
+
245
+
246
+ class Qwen3TTSTokenizerV2DecoderRotatoryEmbedding(nn.Module):
247
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
248
+
249
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, device=None):
250
+ super().__init__()
251
+ # BC: "rope_type" was originally "type"
252
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
253
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
254
+ else:
255
+ self.rope_type = "default"
256
+ self.max_seq_len_cached = config.max_position_embeddings
257
+ self.original_max_seq_len = config.max_position_embeddings
258
+
259
+ self.config = config
260
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
261
+
262
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
263
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
264
+ self.original_inv_freq = self.inv_freq
265
+
266
+ @torch.no_grad()
267
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
268
+ def forward(self, x, position_ids):
269
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
270
+ position_ids_expanded = position_ids[:, None, :].float()
271
+
272
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
273
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
274
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
275
+ emb = torch.cat((freqs, freqs), dim=-1)
276
+ cos = emb.cos() * self.attention_scaling
277
+ sin = emb.sin() * self.attention_scaling
278
+
279
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
280
+
281
+
282
+ class Qwen3TTSTokenizerV2DecoderAttention(nn.Module):
283
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
284
+
285
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):
286
+ super().__init__()
287
+ self.config = config
288
+ self.layer_idx = layer_idx
289
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
290
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
291
+ self.scaling = self.head_dim**-0.5
292
+ self.attention_dropout = config.attention_dropout
293
+ self.is_causal = True
294
+
295
+ self.q_proj = nn.Linear(
296
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
297
+ )
298
+ self.k_proj = nn.Linear(
299
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
300
+ )
301
+ self.v_proj = nn.Linear(
302
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
303
+ )
304
+ self.o_proj = nn.Linear(
305
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
306
+ )
307
+ self.q_norm = nn.Identity()
308
+ self.k_norm = nn.Identity()
309
+ self.sliding_window = config.sliding_window
310
+
311
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
312
+ def forward(
313
+ self,
314
+ hidden_states: torch.Tensor,
315
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
316
+ attention_mask: Optional[torch.Tensor],
317
+ past_key_values: Optional[Cache] = None,
318
+ cache_position: Optional[torch.LongTensor] = None,
319
+ **kwargs: Unpack[FlashAttentionKwargs],
320
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
321
+ input_shape = hidden_states.shape[:-1]
322
+ hidden_shape = (*input_shape, -1, self.head_dim)
323
+
324
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
325
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
326
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
327
+
328
+ cos, sin = position_embeddings
329
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
330
+
331
+ if past_key_values is not None:
332
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
333
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
334
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
335
+
336
+ attention_interface: Callable = eager_attention_forward
337
+ if self.config._attn_implementation != "eager":
338
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
339
+
340
+ attn_output, attn_weights = attention_interface(
341
+ self,
342
+ query_states,
343
+ key_states,
344
+ value_states,
345
+ attention_mask,
346
+ dropout=0.0 if not self.training else self.attention_dropout,
347
+ scaling=self.scaling,
348
+ sliding_window=self.sliding_window, # diff with Llama
349
+ **kwargs,
350
+ )
351
+
352
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
353
+ attn_output = self.o_proj(attn_output)
354
+ return attn_output, attn_weights
355
+
356
+
357
+ class Qwen3TTSTokenizerV2DecoderMlp(nn.Module):
358
+ def __init__(self, config):
359
+ super().__init__()
360
+ self.config = config
361
+ self.hidden_size = config.hidden_size
362
+ self.intermediate_size = config.intermediate_size
363
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
364
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
365
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
366
+ self.act_fn = ACT2FN[config.hidden_act]
367
+
368
+ def forward(self, x):
369
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
370
+ return down_proj
371
+
372
+
373
+ @use_kernel_forward_from_hub("RMSNorm")
374
+ class Qwen3TTSTokenizerV2DecoderRMSNorm(nn.Module):
375
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
376
+ """
377
+ Qwen3TTSTokenizerV2DecoderRMSNorm is equivalent to T5LayerNorm
378
+ """
379
+ super().__init__()
380
+ self.weight = nn.Parameter(torch.ones(hidden_size))
381
+ self.variance_epsilon = eps
382
+
383
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
384
+ input_dtype = hidden_states.dtype
385
+ hidden_states = hidden_states.to(torch.float32)
386
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
387
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
388
+ return self.weight * hidden_states.to(input_dtype)
389
+
390
+ def extra_repr(self):
391
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
392
+
393
+
394
+ class Qwen3TTSTokenizerV2DecoderLayerScale(nn.Module):
395
+ """Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
396
+ This rescales diagonally the residual outputs close to 0, with a learnt scale.
397
+ """
398
+
399
+ def __init__(self, config):
400
+ super().__init__()
401
+ channels = config.hidden_size
402
+ initial_scale = config.layer_scale_initial_scale
403
+ self.scale = nn.Parameter(torch.full((channels,), initial_scale, requires_grad=True))
404
+
405
+ def forward(self, x: torch.Tensor):
406
+ return self.scale * x
407
+
408
+
409
+ class Qwen3TTSTokenizerV2DecoderTransformerLayer(GradientCheckpointingLayer):
410
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):
411
+ super().__init__()
412
+ self.hidden_size = config.hidden_size
413
+ self.self_attn = Qwen3TTSTokenizerV2DecoderAttention(config, layer_idx)
414
+ self.mlp = Qwen3TTSTokenizerV2DecoderMlp(config)
415
+ self.input_layernorm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, config.rms_norm_eps)
416
+ self.post_attention_layernorm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, config.rms_norm_eps)
417
+ self.self_attn_layer_scale = Qwen3TTSTokenizerV2DecoderLayerScale(config)
418
+ self.mlp_layer_scale = Qwen3TTSTokenizerV2DecoderLayerScale(config)
419
+ self.attention_type = "sliding_attention"
420
+
421
+ def forward(
422
+ self,
423
+ hidden_states: torch.Tensor,
424
+ attention_mask: Optional[torch.Tensor] = None,
425
+ position_ids: Optional[torch.LongTensor] = None,
426
+ past_key_values: Optional[Cache] = None,
427
+ use_cache: Optional[bool] = False,
428
+ cache_position: Optional[torch.LongTensor] = None,
429
+ **kwargs,
430
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
431
+ """
432
+ Args:
433
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
434
+ attention_mask (`torch.FloatTensor`, *optional*):
435
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
436
+ query_sequence_length, key_sequence_length)` if default attention is used.
437
+ output_attentions (`bool`, *optional*):
438
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
439
+ returned tensors for more detail.
440
+ use_cache (`bool`, *optional*):
441
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
442
+ (see `past_key_values`).
443
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
444
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
445
+ Indices depicting the position of the input sequence tokens in the sequence
446
+ kwargs (`dict`, *optional*):
447
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
448
+ into the model
449
+ """
450
+ residual = hidden_states
451
+
452
+ hidden_states = self.input_layernorm(hidden_states)
453
+
454
+ # Self Attention
455
+ hidden_states, _ = self.self_attn(
456
+ hidden_states=hidden_states,
457
+ attention_mask=attention_mask,
458
+ position_ids=position_ids,
459
+ past_key_values=past_key_values,
460
+ use_cache=use_cache,
461
+ cache_position=cache_position,
462
+ **kwargs,
463
+ )
464
+ hidden_states = residual + self.self_attn_layer_scale(hidden_states)
465
+
466
+ # Fully Connected
467
+ residual = hidden_states
468
+ hidden_states = self.post_attention_layernorm(hidden_states)
469
+ hidden_states = self.mlp(hidden_states)
470
+ hidden_states = residual + self.mlp_layer_scale(hidden_states)
471
+
472
+ return hidden_states
473
+
474
+
475
+ @auto_docstring
476
+ class Qwen3TTSTokenizerV2DecoderTransformerModel(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
477
+ _can_record_outputs = {
478
+ "hidden_states": Qwen3TTSTokenizerV2DecoderTransformerLayer,
479
+ "attentions": Qwen3TTSTokenizerV2DecoderAttention,
480
+ }
481
+
482
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig):
483
+ super().__init__(config)
484
+ self.layers = nn.ModuleList(
485
+ [Qwen3TTSTokenizerV2DecoderTransformerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
486
+ )
487
+ self.norm = Qwen3TTSTokenizerV2DecoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
488
+ self.rotary_emb = Qwen3TTSTokenizerV2DecoderRotatoryEmbedding(config=config)
489
+ self.gradient_checkpointing = False
490
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
491
+ self.window_size = config.sliding_window
492
+
493
+ self.input_proj = nn.Linear(config.latent_dim, config.hidden_size)
494
+ self.output_proj = nn.Linear(config.hidden_size, config.latent_dim)
495
+
496
+ # Initialize weights and apply final processing
497
+ self.post_init()
498
+
499
+ @check_model_inputs()
500
+ @auto_docstring
501
+ def forward(
502
+ self,
503
+ input_ids=None,
504
+ attention_mask=None,
505
+ position_ids=None,
506
+ past_key_values=None,
507
+ inputs_embeds=None,
508
+ use_cache=None,
509
+ cache_position=None,
510
+ **kwargs,
511
+ ) -> BaseModelOutputWithPast:
512
+ if input_ids is not None:
513
+ raise ValueError("input_ids is not expected")
514
+ if (input_ids is None) ^ (inputs_embeds is not None):
515
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
516
+
517
+ if inputs_embeds is None:
518
+ inputs_embeds = self.embed_tokens(input_ids)
519
+
520
+ inputs_embeds = self.input_proj(inputs_embeds)
521
+
522
+ if use_cache and past_key_values is None:
523
+ past_key_values = DynamicCache(config=self.config)
524
+
525
+ if cache_position is None:
526
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
527
+ cache_position = torch.arange(
528
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
529
+ )
530
+
531
+ if position_ids is None:
532
+ position_ids = cache_position.unsqueeze(0)
533
+
534
+ # It may already have been prepared by e.g. `generate`
535
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
536
+ # Prepare mask arguments
537
+ mask_kwargs = {
538
+ "config": self.config,
539
+ "input_embeds": inputs_embeds,
540
+ "attention_mask": attention_mask,
541
+ "cache_position": cache_position,
542
+ "past_key_values": past_key_values,
543
+ "position_ids": position_ids,
544
+ }
545
+ # Create the masks
546
+ causal_mask_mapping = {
547
+ "full_attention": create_causal_mask(**mask_kwargs),
548
+ }
549
+ # The sliding window alternating layers are not always activated depending on the config
550
+ if self.has_sliding_layers:
551
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
552
+
553
+ hidden_states = inputs_embeds
554
+
555
+ # create position embeddings to be shared across the decoder layers
556
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
557
+
558
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
559
+ hidden_states = decoder_layer(
560
+ hidden_states,
561
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
562
+ position_ids=position_ids,
563
+ past_key_values=past_key_values,
564
+ use_cache=use_cache,
565
+ cache_position=cache_position,
566
+ position_embeddings=position_embeddings,
567
+ **kwargs,
568
+ )
569
+
570
+ hidden_states = self.norm(hidden_states)
571
+ hidden_states = self.output_proj(hidden_states)
572
+ return BaseModelOutputWithPast(
573
+ last_hidden_state=hidden_states,
574
+ past_key_values=past_key_values if use_cache else None,
575
+ )
576
+
577
+
578
+ class SnakeBeta(nn.Module):
579
+ """
580
+ A modified Snake function which uses separate parameters for the magnitude of the periodic components
581
+ Shape:
582
+ - Input: (B, C, T)
583
+ - Output: (B, C, T), same shape as the input
584
+ Parameters:
585
+ - alpha - trainable parameter that controls frequency
586
+ - beta - trainable parameter that controls magnitude
587
+ References:
588
+ - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
589
+ https://huggingface.co/papers/2006.08195
590
+ """
591
+
592
+ def __init__(self, in_features, alpha=1.0):
593
+ super().__init__()
594
+ self.in_features = in_features
595
+
596
+ # initialize alpha
597
+ self.alpha = Parameter(torch.zeros(in_features) * alpha)
598
+ self.beta = Parameter(torch.zeros(in_features) * alpha)
599
+
600
+ self.no_div_by_zero = 0.000000001
601
+
602
+ def forward(self, hidden_states):
603
+ """
604
+ Forward pass of the function.
605
+ Applies the function to the input elementwise.
606
+ SnakeBeta ∶= x + 1/b * sin^2 (xa)
607
+ """
608
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
609
+ beta = self.beta.unsqueeze(0).unsqueeze(-1)
610
+ alpha = torch.exp(alpha)
611
+ beta = torch.exp(beta)
612
+ hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(
613
+ torch.sin(hidden_states * alpha), 2
614
+ )
615
+
616
+ return hidden_states
617
+
618
+
619
+ class Qwen3TTSTokenizerV2DecoderDecoderResidualUnit(nn.Module):
620
+ def __init__(self, dim: int = 16, dilation: int = 1):
621
+ super().__init__()
622
+
623
+ self.act1 = SnakeBeta(dim)
624
+ self.conv1 = Qwen3TTSTokenizerV2CausalConvNet(dim, dim, kernel_size=7, dilation=dilation)
625
+ self.act2 = SnakeBeta(dim)
626
+ self.conv2 = Qwen3TTSTokenizerV2CausalConvNet(dim, dim, kernel_size=1)
627
+
628
+ def forward(self, hidden_state):
629
+ residual = hidden_state
630
+
631
+ hidden_state = self.act1(hidden_state)
632
+ hidden_state = self.conv1(hidden_state)
633
+ hidden_state = self.act2(hidden_state)
634
+ hidden_state = self.conv2(hidden_state)
635
+ return hidden_state + residual
636
+
637
+
638
+ class Qwen3TTSTokenizerV2DecoderDecoderBlock(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
639
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig, layer_idx):
640
+ super().__init__(config)
641
+ in_dim = config.decoder_dim // 2**layer_idx
642
+ out_dim = config.decoder_dim // 2 ** (layer_idx + 1)
643
+ upsample_rate = config.upsample_rates[layer_idx]
644
+
645
+ block = [
646
+ SnakeBeta(in_dim),
647
+ Qwen3TTSTokenizerV2CausalTransConvNet(in_dim, out_dim, 2 * upsample_rate, upsample_rate),
648
+ ]
649
+
650
+ for dilation in (1, 3, 9):
651
+ block.append(Qwen3TTSTokenizerV2DecoderDecoderResidualUnit(out_dim, dilation))
652
+
653
+ self.block = nn.ModuleList(block)
654
+
655
+ def forward(self, hidden):
656
+ for block in self.block:
657
+ hidden = block(hidden)
658
+ return hidden
659
+
660
+
661
+ class EuclideanCodebook(nn.Module):
662
+ def __init__(
663
+ self,
664
+ dim: int,
665
+ codebook_size: int,
666
+ epsilon: float = 1e-5,
667
+ ):
668
+ super().__init__()
669
+ self.dim = dim
670
+ self.codebook_size = codebook_size
671
+ self.epsilon = epsilon
672
+
673
+ self.cluster_usage = nn.Parameter(torch.ones(codebook_size))
674
+ self.embedding_sum = nn.Parameter(torch.zeros(codebook_size, dim))
675
+
676
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
677
+ embedding = self.embedding_sum / self.cluster_usage.clamp(min=self.epsilon)[:, None]
678
+ quantized = F.embedding(codes, embedding)
679
+ return quantized
680
+
681
+
682
+ class VectorQuantization(nn.Module):
683
+ def __init__(
684
+ self,
685
+ dim: int,
686
+ codebook_size: int,
687
+ codebook_dim: Optional[int] = None,
688
+ epsilon: float = 1e-5,
689
+ ):
690
+ super().__init__()
691
+ if codebook_dim is None:
692
+ codebook_dim = dim
693
+
694
+ requires_projection = codebook_dim != dim
695
+
696
+ self.project_out = (
697
+ nn.Linear(codebook_dim, dim) if requires_projection else nn.Identity()
698
+ )
699
+ self.epsilon = epsilon
700
+ self._codebook = EuclideanCodebook(
701
+ dim=codebook_dim,
702
+ codebook_size=codebook_size,
703
+ epsilon=epsilon
704
+ )
705
+ self.codebook_size = codebook_size
706
+
707
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
708
+ quantized = self._codebook.decode(codes)
709
+ quantized = self.project_out(quantized)
710
+ quantized = quantized.transpose(1, 2)
711
+ return quantized
712
+
713
+
714
+ class ResidualVectorQuantization(nn.Module):
715
+ def __init__(self, *, num_quantizers: int, **kwargs):
716
+ super().__init__()
717
+ self.layers = nn.ModuleList(
718
+ [VectorQuantization(**kwargs) for _ in range(num_quantizers)]
719
+ )
720
+
721
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
722
+ quantized = torch.zeros([1], device=codes.device)[0]
723
+ for idx, layer_codes in enumerate(codes):
724
+ layer = self.layers[idx]
725
+ assert isinstance(layer, VectorQuantization)
726
+ quantized = quantized + layer.decode(layer_codes)
727
+ return quantized
728
+
729
+
730
+ class ResidualVectorQuantizer(nn.Module):
731
+ def __init__(
732
+ self,
733
+ dimension: int = 128,
734
+ input_dimension: Optional[int] = None,
735
+ output_dimension: Optional[int] = None,
736
+ n_q: int = 8,
737
+ q_dropout: bool = False,
738
+ no_quantization_rate: float = 0.0,
739
+ bins: int = 1024,
740
+ decay: float = 0.99,
741
+ force_projection: bool = False,
742
+ ):
743
+ super().__init__()
744
+ self.max_n_q = n_q
745
+ self.n_q = n_q
746
+ self.q_dropout = q_dropout
747
+ self.no_quantization_rate = no_quantization_rate
748
+ self.dimension = dimension
749
+ self.input_dimension = input_dimension or dimension
750
+ self.output_dimension = output_dimension or dimension
751
+ self.bins = bins
752
+ self.decay = decay
753
+ self.input_proj: torch.nn.Module
754
+ self.output_proj: torch.nn.Module
755
+ if self.input_dimension == self.dimension and not force_projection:
756
+ self.input_proj = torch.nn.Identity()
757
+ else:
758
+ self.input_proj = torch.nn.Conv1d(
759
+ self.input_dimension, self.dimension, 1, bias=False
760
+ )
761
+ if self.output_dimension == self.dimension and not force_projection:
762
+ self.output_proj = torch.nn.Identity()
763
+ else:
764
+ self.output_proj = torch.nn.Conv1d(
765
+ self.dimension, self.output_dimension, 1, bias=False
766
+ )
767
+ self.vq = ResidualVectorQuantization(
768
+ dim=self.dimension,
769
+ codebook_size=self.bins,
770
+ num_quantizers=self.n_q
771
+ )
772
+
773
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
774
+ codes = codes.transpose(0, 1)
775
+ quantized = self.vq.decode(codes)
776
+ quantized = self.output_proj(quantized)
777
+ return quantized
778
+
779
+
780
+ class SplitResidualVectorQuantizer(nn.Module):
781
+ """Residual Vector Quantizer with separate projections for the first quantizer and the rest.
782
+
783
+ Args:
784
+ n_q (int): Number of residual vector quantizers used.
785
+ n_semantic_q (int): Number of residual vector quantizers used for the semantic quantizer.
786
+ **kwargs: Arguments to the constructor of `ResidualVectorQuantizer` that are shared between both.
787
+ """
788
+
789
+ def __init__(
790
+ self,
791
+ *,
792
+ n_q: int = 8,
793
+ n_q_semantic: int = 1,
794
+ **kwargs,
795
+ ):
796
+ super().__init__()
797
+ assert n_q > n_q_semantic, (
798
+ f"Number of quantizers {n_q} must be larger "
799
+ f"than the number of semantic quantizers {n_q_semantic}."
800
+ )
801
+ self.max_n_q = n_q
802
+ self.n_q_semantic = n_q_semantic
803
+ self.n_q_acoustic = n_q - n_q_semantic
804
+ q_dropout = kwargs.pop("q_dropout", False)
805
+ self.rvq_first = ResidualVectorQuantizer(
806
+ n_q=n_q_semantic, force_projection=True, q_dropout=False, **kwargs
807
+ )
808
+ self.rvq_rest = ResidualVectorQuantizer(
809
+ n_q=n_q - n_q_semantic,
810
+ force_projection=True,
811
+ q_dropout=q_dropout,
812
+ **kwargs,
813
+ )
814
+
815
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
816
+ """Decode the given codes to the quantized representation."""
817
+ # codes is [B, K, T], with T frames, K nb of codebooks.
818
+ quantized = self.rvq_first.decode(codes[:, : self.n_q_semantic])
819
+ if codes.shape[1] > self.n_q_semantic:
820
+ quantized += self.rvq_rest.decode(codes[:, self.n_q_semantic :])
821
+ return quantized
822
+
823
+
824
+ class Qwen3TTSTokenizerV2Decoder(Qwen3TTSTokenizerV2DecoderPreTrainedModel):
825
+ def __init__(self, config: Qwen3TTSTokenizerV2DecoderConfig):
826
+ super().__init__(config)
827
+ self.total_upsample = np.prod(config.upsample_rates + config.upsampling_ratios)
828
+ self.pre_transformer = Qwen3TTSTokenizerV2DecoderTransformerModel._from_config(config)
829
+
830
+ self.quantizer = SplitResidualVectorQuantizer(
831
+ dimension=config.codebook_dim // 2,
832
+ n_q=config.num_quantizers,
833
+ n_q_semantic=1,
834
+ bins=config.codebook_size,
835
+ input_dimension=config.codebook_dim,
836
+ output_dimension=config.codebook_dim,
837
+ )
838
+
839
+ self.pre_conv = Qwen3TTSTokenizerV2CausalConvNet(
840
+ config.codebook_dim,
841
+ config.latent_dim,
842
+ kernel_size=3,
843
+ )
844
+
845
+ upsample = []
846
+ for factor in config.upsampling_ratios:
847
+ upsample.append(
848
+ nn.ModuleList(
849
+ [
850
+ Qwen3TTSTokenizerV2CausalTransConvNet(config.latent_dim, config.latent_dim, factor, factor),
851
+ Qwen3TTSTokenizerV2ConvNeXtBlock(config.latent_dim),
852
+ ]
853
+ )
854
+ )
855
+ self.upsample = nn.ModuleList(upsample)
856
+
857
+ decoder = [Qwen3TTSTokenizerV2CausalConvNet(config.latent_dim, config.decoder_dim, 7)]
858
+ for i in range(len(config.upsample_rates)):
859
+ decoder.append(Qwen3TTSTokenizerV2DecoderDecoderBlock(config, i))
860
+ output_dim = config.decoder_dim // 2 ** len(config.upsample_rates)
861
+ decoder += [
862
+ SnakeBeta(output_dim),
863
+ Qwen3TTSTokenizerV2CausalConvNet(output_dim, 1, 7),
864
+ ]
865
+ self.decoder = nn.ModuleList(decoder)
866
+
867
+ self.post_init()
868
+
869
+ def forward(self, codes):
870
+ if codes.shape[1] != self.config.num_quantizers:
871
+ raise ValueError(f"Expected {self.config.num_quantizers} layer of codes, got {codes.shape[1]}")
872
+
873
+ hidden = self.quantizer.decode(codes)
874
+ hidden = self.pre_conv(hidden).transpose(1, 2)
875
+
876
+ hidden = self.pre_transformer(inputs_embeds=hidden).last_hidden_state
877
+ hidden = hidden.permute(0, 2, 1)
878
+ for blocks in self.upsample:
879
+ for block in blocks:
880
+ hidden = block(hidden)
881
+ wav = hidden
882
+ for block in self.decoder:
883
+ wav = block(wav)
884
+ return wav.clamp(min=-1, max=1)
885
+
886
+ def chunked_decode(self, codes, chunk_size=300, left_context_size=25):
887
+ wavs = []
888
+ start_index = 0
889
+ while start_index < codes.shape[-1]:
890
+ end_index = min(start_index + chunk_size, codes.shape[-1])
891
+ context_size = left_context_size if start_index - left_context_size > 0 else start_index
892
+ codes_chunk = codes[..., start_index - context_size : end_index]
893
+ wav_chunk = self(codes_chunk)
894
+ wavs.append(wav_chunk[..., context_size * self.total_upsample :])
895
+ start_index = end_index
896
+ return torch.cat(wavs, dim=-1)
897
+
898
+
899
+ class Qwen3TTSTokenizerV2Encoder(MimiModel):
900
+ def __init__(self, config: MimiConfig):
901
+ super().__init__(config)
902
+ self.config = config
903
+
904
+ self.upsample = None
905
+ self.decoder_transformer = None
906
+ self.decoder = None
907
+
908
+ self.post_init()
909
+
910
+
911
+ @auto_docstring
912
+ class Qwen3TTSTokenizerV2PreTrainedModel(PreTrainedModel):
913
+ config: Qwen3TTSTokenizerV2Config
914
+ base_model_prefix = "model"
915
+ supports_gradient_checkpointing = True
916
+ _skip_keys_device_placement = "past_key_values"
917
+ _supports_flash_attn = True
918
+ _supports_sdpa = True
919
+ _can_compile_fullgraph = False
920
+ _supports_attention_backend = True
921
+
922
+
923
+ @auto_docstring(
924
+ custom_intro="""
925
+ The Qwen3TTSTokenizerV2 model.
926
+ """
927
+ )
928
+ class Qwen3TTSTokenizerV2Model(Qwen3TTSTokenizerV2PreTrainedModel):
929
+ def __init__(self, config: Qwen3TTSTokenizerV2Config):
930
+ super().__init__(config)
931
+ self.config = config
932
+
933
+ self.encoder_valid_num_quantizers = config.encoder_valid_num_quantizers
934
+
935
+ self.input_sample_rate = config.input_sample_rate
936
+ self.output_sample_rate = config.output_sample_rate
937
+
938
+ self.decode_upsample_rate = config.decode_upsample_rate
939
+ self.encode_downsample_rate = config.encode_downsample_rate
940
+
941
+ self.encoder = Qwen3TTSTokenizerV2Encoder._from_config(self.config.encoder_config)
942
+ self.decoder = Qwen3TTSTokenizerV2Decoder._from_config(self.config.decoder_config)
943
+
944
+ self.post_init()
945
+
946
+ def get_model_type(self):
947
+ return self.config.model_type
948
+
949
+ def get_input_sample_rate(self):
950
+ return self.input_sample_rate
951
+
952
+ def get_output_sample_rate(self):
953
+ return self.output_sample_rate
954
+
955
+ def get_encode_downsample_rate(self):
956
+ return self.encode_downsample_rate
957
+
958
+ def get_decode_upsample_rate(self):
959
+ return self.decode_upsample_rate
960
+
961
+ def encode(
962
+ self,
963
+ input_values: torch.Tensor,
964
+ padding_mask: Optional[torch.Tensor] = None,
965
+ return_dict: Optional[bool] = None,
966
+ ) -> Union[tuple[torch.Tensor, Optional[torch.Tensor]], Qwen3TTSTokenizerV2EncoderOutput]:
967
+ """
968
+ Encodes the input audio waveform into discrete codes.
969
+
970
+ Args:
971
+ input_values (`torch.Tensor` of shape `(batch_size, sequence_length)`):
972
+ Float values of the input audio waveform.
973
+ padding_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`):
974
+ Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
975
+ for *masked*.
976
+ return_dict (`bool`, *optional*):
977
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
978
+ """
979
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
980
+
981
+ encoded_frames = self.encoder.encode(input_values=input_values.unsqueeze(1),
982
+ return_dict=True)
983
+ audio_codes = encoded_frames.audio_codes[:, :self.encoder_valid_num_quantizers]
984
+ audio_codes = [code[..., :-(-mask.sum() // self.encode_downsample_rate)].transpose(0, 1) for code, mask in zip(audio_codes, padding_mask)]
985
+
986
+ if not return_dict:
987
+ return (
988
+ audio_codes,
989
+ )
990
+
991
+ return Qwen3TTSTokenizerV2EncoderOutput(audio_codes)
992
+
993
+ def decode(
994
+ self,
995
+ audio_codes: torch.Tensor,
996
+ return_dict: Optional[bool] = None,
997
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], Qwen3TTSTokenizerV2DecoderOutput]:
998
+ """
999
+ Decodes the given frames into an output audio waveform.
1000
+
1001
+ Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
1002
+ trimmed.
1003
+
1004
+ Args:
1005
+ audio_codes (`torch.LongTensor` of shape `(batch_size, codes_length, num_quantizers)`, *optional*):
1006
+ Discret code embeddings computed using `model.encode`.
1007
+ return_dict (`bool`, *optional*):
1008
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1009
+
1010
+ """
1011
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1012
+ audio_lengths = (audio_codes[..., 0] > -1).sum(1) * self.decode_upsample_rate
1013
+
1014
+ audio_codes = torch.clamp(audio_codes, min=0)
1015
+ audio_values = self.decoder.chunked_decode(audio_codes.transpose(1, 2)).squeeze(1)
1016
+
1017
+ audio_values = [a[:l] for a, l in zip(audio_values, audio_lengths)]
1018
+
1019
+ if not return_dict:
1020
+ return (
1021
+ audio_values,
1022
+ )
1023
+
1024
+ return Qwen3TTSTokenizerV2DecoderOutput(audio_values)
1025
+
1026
+
1027
+ __all__ = ["Qwen3TTSTokenizerV2Model", "Qwen3TTSTokenizerV2PreTrainedModel"]