videopython-chatterbox 0.1.7.post1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chatterbox/__init__.py +14 -0
- chatterbox/models/__init__.py +0 -0
- chatterbox/models/s3gen/__init__.py +2 -0
- chatterbox/models/s3gen/configs.py +10 -0
- chatterbox/models/s3gen/const.py +2 -0
- chatterbox/models/s3gen/decoder.py +333 -0
- chatterbox/models/s3gen/f0_predictor.py +55 -0
- chatterbox/models/s3gen/flow.py +198 -0
- chatterbox/models/s3gen/flow_matching.py +246 -0
- chatterbox/models/s3gen/hifigan.py +474 -0
- chatterbox/models/s3gen/matcha/decoder.py +443 -0
- chatterbox/models/s3gen/matcha/flow_matching.py +129 -0
- chatterbox/models/s3gen/matcha/text_encoder.py +413 -0
- chatterbox/models/s3gen/matcha/transformer.py +316 -0
- chatterbox/models/s3gen/s3gen.py +362 -0
- chatterbox/models/s3gen/transformer/__init__.py +0 -0
- chatterbox/models/s3gen/transformer/activation.py +84 -0
- chatterbox/models/s3gen/transformer/attention.py +330 -0
- chatterbox/models/s3gen/transformer/convolution.py +145 -0
- chatterbox/models/s3gen/transformer/embedding.py +294 -0
- chatterbox/models/s3gen/transformer/encoder_layer.py +236 -0
- chatterbox/models/s3gen/transformer/positionwise_feed_forward.py +115 -0
- chatterbox/models/s3gen/transformer/subsampling.py +383 -0
- chatterbox/models/s3gen/transformer/upsample_encoder.py +318 -0
- chatterbox/models/s3gen/utils/class_utils.py +71 -0
- chatterbox/models/s3gen/utils/intmeanflow.py +36 -0
- chatterbox/models/s3gen/utils/mask.py +194 -0
- chatterbox/models/s3gen/utils/mel.py +85 -0
- chatterbox/models/s3gen/xvector.py +428 -0
- chatterbox/models/s3tokenizer/__init__.py +30 -0
- chatterbox/models/s3tokenizer/s3tokenizer.py +168 -0
- chatterbox/models/t3/__init__.py +1 -0
- chatterbox/models/t3/inference/alignment_stream_analyzer.py +181 -0
- chatterbox/models/t3/inference/t3_hf_backend.py +116 -0
- chatterbox/models/t3/llama_configs.py +73 -0
- chatterbox/models/t3/modules/cond_enc.py +97 -0
- chatterbox/models/t3/modules/learned_pos_emb.py +32 -0
- chatterbox/models/t3/modules/perceiver.py +212 -0
- chatterbox/models/t3/modules/t3_config.py +41 -0
- chatterbox/models/t3/t3.py +490 -0
- chatterbox/models/tokenizers/__init__.py +1 -0
- chatterbox/models/tokenizers/tokenizer.py +313 -0
- chatterbox/models/utils.py +4 -0
- chatterbox/models/voice_encoder/__init__.py +1 -0
- chatterbox/models/voice_encoder/config.py +18 -0
- chatterbox/models/voice_encoder/melspec.py +78 -0
- chatterbox/models/voice_encoder/voice_encoder.py +274 -0
- chatterbox/mtl_tts.py +317 -0
- chatterbox/tts.py +272 -0
- chatterbox/tts_turbo.py +296 -0
- chatterbox/vc.py +104 -0
- videopython_chatterbox-0.1.7.post1.dist-info/METADATA +154 -0
- videopython_chatterbox-0.1.7.post1.dist-info/RECORD +56 -0
- videopython_chatterbox-0.1.7.post1.dist-info/WHEEL +4 -0
- videopython_chatterbox-0.1.7.post1.dist-info/licenses/LICENSE +21 -0
- videopython_chatterbox-0.1.7.post1.dist-info/licenses/NOTICE +29 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
from typing import Any, Dict, Optional
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
from diffusers.models.attention import (
|
|
6
|
+
GEGLU,
|
|
7
|
+
GELU,
|
|
8
|
+
AdaLayerNorm,
|
|
9
|
+
AdaLayerNormZero,
|
|
10
|
+
ApproximateGELU,
|
|
11
|
+
)
|
|
12
|
+
from diffusers.models.attention_processor import Attention
|
|
13
|
+
from diffusers.models.lora import LoRACompatibleLinear
|
|
14
|
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SnakeBeta(nn.Module):
|
|
18
|
+
"""
|
|
19
|
+
A modified Snake function which uses separate parameters for the magnitude of the periodic components
|
|
20
|
+
Shape:
|
|
21
|
+
- Input: (B, C, T)
|
|
22
|
+
- Output: (B, C, T), same shape as the input
|
|
23
|
+
Parameters:
|
|
24
|
+
- alpha - trainable parameter that controls frequency
|
|
25
|
+
- beta - trainable parameter that controls magnitude
|
|
26
|
+
References:
|
|
27
|
+
- This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
|
28
|
+
https://arxiv.org/abs/2006.08195
|
|
29
|
+
Examples:
|
|
30
|
+
>>> a1 = snakebeta(256)
|
|
31
|
+
>>> x = torch.randn(256)
|
|
32
|
+
>>> x = a1(x)
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
|
|
36
|
+
"""
|
|
37
|
+
Initialization.
|
|
38
|
+
INPUT:
|
|
39
|
+
- in_features: shape of the input
|
|
40
|
+
- alpha - trainable parameter that controls frequency
|
|
41
|
+
- beta - trainable parameter that controls magnitude
|
|
42
|
+
alpha is initialized to 1 by default, higher values = higher-frequency.
|
|
43
|
+
beta is initialized to 1 by default, higher values = higher-magnitude.
|
|
44
|
+
alpha will be trained along with the rest of your model.
|
|
45
|
+
"""
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.in_features = out_features if isinstance(out_features, list) else [out_features]
|
|
48
|
+
self.proj = LoRACompatibleLinear(in_features, out_features)
|
|
49
|
+
|
|
50
|
+
# initialize alpha
|
|
51
|
+
self.alpha_logscale = alpha_logscale
|
|
52
|
+
if self.alpha_logscale: # log scale alphas initialized to zeros
|
|
53
|
+
self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
|
|
54
|
+
self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
|
|
55
|
+
else: # linear scale alphas initialized to ones
|
|
56
|
+
self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
|
|
57
|
+
self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
|
|
58
|
+
|
|
59
|
+
self.alpha.requires_grad = alpha_trainable
|
|
60
|
+
self.beta.requires_grad = alpha_trainable
|
|
61
|
+
|
|
62
|
+
self.no_div_by_zero = 0.000000001
|
|
63
|
+
|
|
64
|
+
def forward(self, x):
|
|
65
|
+
"""
|
|
66
|
+
Forward pass of the function.
|
|
67
|
+
Applies the function to the input elementwise.
|
|
68
|
+
SnakeBeta ∶= x + 1/b * sin^2 (xa)
|
|
69
|
+
"""
|
|
70
|
+
x = self.proj(x)
|
|
71
|
+
if self.alpha_logscale:
|
|
72
|
+
alpha = torch.exp(self.alpha)
|
|
73
|
+
beta = torch.exp(self.beta)
|
|
74
|
+
else:
|
|
75
|
+
alpha = self.alpha
|
|
76
|
+
beta = self.beta
|
|
77
|
+
|
|
78
|
+
x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
|
|
79
|
+
|
|
80
|
+
return x
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class FeedForward(nn.Module):
|
|
84
|
+
r"""
|
|
85
|
+
A feed-forward layer.
|
|
86
|
+
|
|
87
|
+
Parameters:
|
|
88
|
+
dim (`int`): The number of channels in the input.
|
|
89
|
+
dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
|
|
90
|
+
mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
|
|
91
|
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
|
92
|
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
|
93
|
+
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
dim: int,
|
|
99
|
+
dim_out: Optional[int] = None,
|
|
100
|
+
mult: int = 4,
|
|
101
|
+
dropout: float = 0.0,
|
|
102
|
+
activation_fn: str = "geglu",
|
|
103
|
+
final_dropout: bool = False,
|
|
104
|
+
):
|
|
105
|
+
super().__init__()
|
|
106
|
+
inner_dim = int(dim * mult)
|
|
107
|
+
dim_out = dim_out if dim_out is not None else dim
|
|
108
|
+
|
|
109
|
+
if activation_fn == "gelu":
|
|
110
|
+
act_fn = GELU(dim, inner_dim)
|
|
111
|
+
if activation_fn == "gelu-approximate":
|
|
112
|
+
act_fn = GELU(dim, inner_dim, approximate="tanh")
|
|
113
|
+
elif activation_fn == "geglu":
|
|
114
|
+
act_fn = GEGLU(dim, inner_dim)
|
|
115
|
+
elif activation_fn == "geglu-approximate":
|
|
116
|
+
act_fn = ApproximateGELU(dim, inner_dim)
|
|
117
|
+
elif activation_fn == "snakebeta":
|
|
118
|
+
act_fn = SnakeBeta(dim, inner_dim)
|
|
119
|
+
|
|
120
|
+
self.net = nn.ModuleList([])
|
|
121
|
+
# project in
|
|
122
|
+
self.net.append(act_fn)
|
|
123
|
+
# project dropout
|
|
124
|
+
self.net.append(nn.Dropout(dropout))
|
|
125
|
+
# project out
|
|
126
|
+
self.net.append(LoRACompatibleLinear(inner_dim, dim_out))
|
|
127
|
+
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
|
128
|
+
if final_dropout:
|
|
129
|
+
self.net.append(nn.Dropout(dropout))
|
|
130
|
+
|
|
131
|
+
def forward(self, hidden_states):
|
|
132
|
+
for module in self.net:
|
|
133
|
+
hidden_states = module(hidden_states)
|
|
134
|
+
return hidden_states
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@maybe_allow_in_graph
|
|
138
|
+
class BasicTransformerBlock(nn.Module):
|
|
139
|
+
r"""
|
|
140
|
+
A basic Transformer block.
|
|
141
|
+
|
|
142
|
+
Parameters:
|
|
143
|
+
dim (`int`): The number of channels in the input and output.
|
|
144
|
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
|
145
|
+
attention_head_dim (`int`): The number of channels in each head.
|
|
146
|
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
|
147
|
+
cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
|
|
148
|
+
only_cross_attention (`bool`, *optional*):
|
|
149
|
+
Whether to use only cross-attention layers. In this case two cross attention layers are used.
|
|
150
|
+
double_self_attention (`bool`, *optional*):
|
|
151
|
+
Whether to use two self-attention layers. In this case no cross attention layers are used.
|
|
152
|
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
|
153
|
+
num_embeds_ada_norm (:
|
|
154
|
+
obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
|
|
155
|
+
attention_bias (:
|
|
156
|
+
obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
def __init__(
|
|
160
|
+
self,
|
|
161
|
+
dim: int,
|
|
162
|
+
num_attention_heads: int,
|
|
163
|
+
attention_head_dim: int,
|
|
164
|
+
dropout=0.0,
|
|
165
|
+
cross_attention_dim: Optional[int] = None,
|
|
166
|
+
activation_fn: str = "geglu",
|
|
167
|
+
num_embeds_ada_norm: Optional[int] = None,
|
|
168
|
+
attention_bias: bool = False,
|
|
169
|
+
only_cross_attention: bool = False,
|
|
170
|
+
double_self_attention: bool = False,
|
|
171
|
+
upcast_attention: bool = False,
|
|
172
|
+
norm_elementwise_affine: bool = True,
|
|
173
|
+
norm_type: str = "layer_norm",
|
|
174
|
+
final_dropout: bool = False,
|
|
175
|
+
):
|
|
176
|
+
super().__init__()
|
|
177
|
+
self.only_cross_attention = only_cross_attention
|
|
178
|
+
|
|
179
|
+
self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
|
|
180
|
+
self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
|
|
181
|
+
|
|
182
|
+
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
|
|
185
|
+
f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
# Define 3 blocks. Each block has its own normalization layer.
|
|
189
|
+
# 1. Self-Attn
|
|
190
|
+
if self.use_ada_layer_norm:
|
|
191
|
+
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
|
|
192
|
+
elif self.use_ada_layer_norm_zero:
|
|
193
|
+
self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
|
|
194
|
+
else:
|
|
195
|
+
self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
|
|
196
|
+
self.attn1 = Attention(
|
|
197
|
+
query_dim=dim,
|
|
198
|
+
heads=num_attention_heads,
|
|
199
|
+
dim_head=attention_head_dim,
|
|
200
|
+
dropout=dropout,
|
|
201
|
+
bias=attention_bias,
|
|
202
|
+
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
|
203
|
+
upcast_attention=upcast_attention,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# 2. Cross-Attn
|
|
207
|
+
if cross_attention_dim is not None or double_self_attention:
|
|
208
|
+
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
|
|
209
|
+
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
|
|
210
|
+
# the second cross attention block.
|
|
211
|
+
self.norm2 = (
|
|
212
|
+
AdaLayerNorm(dim, num_embeds_ada_norm)
|
|
213
|
+
if self.use_ada_layer_norm
|
|
214
|
+
else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
|
|
215
|
+
)
|
|
216
|
+
self.attn2 = Attention(
|
|
217
|
+
query_dim=dim,
|
|
218
|
+
cross_attention_dim=cross_attention_dim if not double_self_attention else None,
|
|
219
|
+
heads=num_attention_heads,
|
|
220
|
+
dim_head=attention_head_dim,
|
|
221
|
+
dropout=dropout,
|
|
222
|
+
bias=attention_bias,
|
|
223
|
+
upcast_attention=upcast_attention,
|
|
224
|
+
# scale_qk=False, # uncomment this to not to use flash attention
|
|
225
|
+
) # is self-attn if encoder_hidden_states is none
|
|
226
|
+
else:
|
|
227
|
+
self.norm2 = None
|
|
228
|
+
self.attn2 = None
|
|
229
|
+
|
|
230
|
+
# 3. Feed-forward
|
|
231
|
+
self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
|
|
232
|
+
self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
|
|
233
|
+
|
|
234
|
+
# let chunk size default to None
|
|
235
|
+
self._chunk_size = None
|
|
236
|
+
self._chunk_dim = 0
|
|
237
|
+
|
|
238
|
+
def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
|
|
239
|
+
# Sets chunk feed-forward
|
|
240
|
+
self._chunk_size = chunk_size
|
|
241
|
+
self._chunk_dim = dim
|
|
242
|
+
|
|
243
|
+
def forward(
|
|
244
|
+
self,
|
|
245
|
+
hidden_states: torch.FloatTensor,
|
|
246
|
+
attention_mask: Optional[torch.FloatTensor] = None,
|
|
247
|
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
|
248
|
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
|
249
|
+
timestep: Optional[torch.LongTensor] = None,
|
|
250
|
+
cross_attention_kwargs: Dict[str, Any] = None,
|
|
251
|
+
class_labels: Optional[torch.LongTensor] = None,
|
|
252
|
+
):
|
|
253
|
+
# Notice that normalization is always applied before the real computation in the following blocks.
|
|
254
|
+
# 1. Self-Attention
|
|
255
|
+
if self.use_ada_layer_norm:
|
|
256
|
+
norm_hidden_states = self.norm1(hidden_states, timestep)
|
|
257
|
+
elif self.use_ada_layer_norm_zero:
|
|
258
|
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
|
259
|
+
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
|
|
260
|
+
)
|
|
261
|
+
else:
|
|
262
|
+
norm_hidden_states = self.norm1(hidden_states)
|
|
263
|
+
|
|
264
|
+
cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
|
|
265
|
+
|
|
266
|
+
attn_output = self.attn1(
|
|
267
|
+
norm_hidden_states,
|
|
268
|
+
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
|
|
269
|
+
attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
|
|
270
|
+
**cross_attention_kwargs,
|
|
271
|
+
)
|
|
272
|
+
if self.use_ada_layer_norm_zero:
|
|
273
|
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
|
274
|
+
hidden_states = attn_output + hidden_states
|
|
275
|
+
|
|
276
|
+
# 2. Cross-Attention
|
|
277
|
+
if self.attn2 is not None:
|
|
278
|
+
norm_hidden_states = (
|
|
279
|
+
self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
attn_output = self.attn2(
|
|
283
|
+
norm_hidden_states,
|
|
284
|
+
encoder_hidden_states=encoder_hidden_states,
|
|
285
|
+
attention_mask=encoder_attention_mask,
|
|
286
|
+
**cross_attention_kwargs,
|
|
287
|
+
)
|
|
288
|
+
hidden_states = attn_output + hidden_states
|
|
289
|
+
|
|
290
|
+
# 3. Feed-forward
|
|
291
|
+
norm_hidden_states = self.norm3(hidden_states)
|
|
292
|
+
|
|
293
|
+
if self.use_ada_layer_norm_zero:
|
|
294
|
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
|
295
|
+
|
|
296
|
+
if self._chunk_size is not None:
|
|
297
|
+
# "feed_forward_chunk_size" can be used to save memory
|
|
298
|
+
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
|
|
299
|
+
raise ValueError(
|
|
300
|
+
f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
|
|
304
|
+
ff_output = torch.cat(
|
|
305
|
+
[self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
|
|
306
|
+
dim=self._chunk_dim,
|
|
307
|
+
)
|
|
308
|
+
else:
|
|
309
|
+
ff_output = self.ff(norm_hidden_states)
|
|
310
|
+
|
|
311
|
+
if self.use_ada_layer_norm_zero:
|
|
312
|
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
|
313
|
+
|
|
314
|
+
hidden_states = ff_output + hidden_states
|
|
315
|
+
|
|
316
|
+
return hidden_states
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
# Modified from CosyVoice https://github.com/FunAudioLLM/CosyVoice
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import torch
|
|
19
|
+
import torchaudio as ta
|
|
20
|
+
from functools import lru_cache
|
|
21
|
+
from typing import Optional
|
|
22
|
+
|
|
23
|
+
from ..s3tokenizer import S3_SR, SPEECH_VOCAB_SIZE, S3Tokenizer
|
|
24
|
+
from .const import S3GEN_SR
|
|
25
|
+
from .flow import CausalMaskedDiffWithXvec
|
|
26
|
+
from .xvector import CAMPPlus
|
|
27
|
+
from .utils.mel import mel_spectrogram
|
|
28
|
+
from .f0_predictor import ConvRNNF0Predictor
|
|
29
|
+
from .hifigan import HiFTGenerator
|
|
30
|
+
from .transformer.upsample_encoder import UpsampleConformerEncoder
|
|
31
|
+
from .flow_matching import CausalConditionalCFM
|
|
32
|
+
from .decoder import ConditionalDecoder
|
|
33
|
+
from .configs import CFM_PARAMS
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def drop_invalid_tokens(x):
|
|
37
|
+
assert len(x.shape) <= 2 and x.shape[0] == 1, "only batch size of one allowed for now"
|
|
38
|
+
return x[x < SPEECH_VOCAB_SIZE]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# TODO: global resampler cache
|
|
42
|
+
@lru_cache(100)
|
|
43
|
+
def get_resampler(src_sr, dst_sr, device):
|
|
44
|
+
return ta.transforms.Resample(src_sr, dst_sr).to(device)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class S3Token2Mel(torch.nn.Module):
|
|
48
|
+
"""
|
|
49
|
+
S3Gen's CFM decoder maps S3 speech tokens to mel-spectrograms.
|
|
50
|
+
|
|
51
|
+
TODO: make these modules configurable?
|
|
52
|
+
"""
|
|
53
|
+
def __init__(self, meanflow=False):
|
|
54
|
+
super().__init__()
|
|
55
|
+
self.tokenizer = S3Tokenizer("speech_tokenizer_v2_25hz")
|
|
56
|
+
self.mel_extractor = mel_spectrogram # TODO: make it a torch module?
|
|
57
|
+
self.speaker_encoder = CAMPPlus(
|
|
58
|
+
# NOTE: This doesn't affect inference. It turns off activation checkpointing
|
|
59
|
+
# (a training optimization), which causes a crazy DDP error with accelerate
|
|
60
|
+
memory_efficient=False,
|
|
61
|
+
)
|
|
62
|
+
self.meanflow = meanflow
|
|
63
|
+
|
|
64
|
+
encoder = UpsampleConformerEncoder(
|
|
65
|
+
output_size=512,
|
|
66
|
+
attention_heads=8,
|
|
67
|
+
linear_units=2048,
|
|
68
|
+
num_blocks=6,
|
|
69
|
+
dropout_rate=0.1,
|
|
70
|
+
positional_dropout_rate=0.1,
|
|
71
|
+
attention_dropout_rate=0.1,
|
|
72
|
+
normalize_before=True,
|
|
73
|
+
input_layer='linear',
|
|
74
|
+
pos_enc_layer_type='rel_pos_espnet',
|
|
75
|
+
selfattention_layer_type='rel_selfattn',
|
|
76
|
+
input_size=512,
|
|
77
|
+
use_cnn_module=False,
|
|
78
|
+
macaron_style=False,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
estimator = ConditionalDecoder(
|
|
82
|
+
in_channels=320,
|
|
83
|
+
out_channels=80,
|
|
84
|
+
causal=True,
|
|
85
|
+
channels=[256],
|
|
86
|
+
dropout=0.0,
|
|
87
|
+
attention_head_dim=64,
|
|
88
|
+
n_blocks=4,
|
|
89
|
+
num_mid_blocks=12,
|
|
90
|
+
num_heads=8,
|
|
91
|
+
act_fn='gelu',
|
|
92
|
+
meanflow=self.meanflow,
|
|
93
|
+
)
|
|
94
|
+
cfm_params = CFM_PARAMS
|
|
95
|
+
decoder = CausalConditionalCFM(
|
|
96
|
+
spk_emb_dim=80,
|
|
97
|
+
cfm_params=cfm_params,
|
|
98
|
+
estimator=estimator,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
self.flow = CausalMaskedDiffWithXvec(
|
|
102
|
+
encoder=encoder,
|
|
103
|
+
decoder=decoder
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
self.resamplers = {}
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def device(self):
|
|
110
|
+
params = self.tokenizer.parameters()
|
|
111
|
+
return next(params).device
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def dtype(self):
|
|
115
|
+
params = self.flow.parameters()
|
|
116
|
+
return next(params).dtype
|
|
117
|
+
|
|
118
|
+
def embed_ref(
|
|
119
|
+
self,
|
|
120
|
+
ref_wav: torch.Tensor,
|
|
121
|
+
ref_sr: int,
|
|
122
|
+
device="auto",
|
|
123
|
+
ref_fade_out=True,
|
|
124
|
+
):
|
|
125
|
+
device = self.device if device == "auto" else device
|
|
126
|
+
if isinstance(ref_wav, np.ndarray):
|
|
127
|
+
ref_wav = torch.from_numpy(ref_wav).float()
|
|
128
|
+
|
|
129
|
+
if ref_wav.device != device:
|
|
130
|
+
ref_wav = ref_wav.to(device)
|
|
131
|
+
|
|
132
|
+
if len(ref_wav.shape) == 1:
|
|
133
|
+
ref_wav = ref_wav.unsqueeze(0) # (B, L)
|
|
134
|
+
|
|
135
|
+
if ref_wav.size(1) > 10 * ref_sr:
|
|
136
|
+
print("WARNING: s3gen received ref longer than 10s")
|
|
137
|
+
|
|
138
|
+
ref_wav_24 = ref_wav
|
|
139
|
+
if ref_sr != S3GEN_SR:
|
|
140
|
+
ref_wav_24 = get_resampler(ref_sr, S3GEN_SR, device)(ref_wav)
|
|
141
|
+
ref_wav_24 = ref_wav_24.to(device=device, dtype=self.dtype)
|
|
142
|
+
|
|
143
|
+
ref_mels_24 = self.mel_extractor(ref_wav_24).transpose(1, 2).to(dtype=self.dtype)
|
|
144
|
+
ref_mels_24_len = None
|
|
145
|
+
|
|
146
|
+
# Resample to 16kHz
|
|
147
|
+
ref_wav_16 = ref_wav
|
|
148
|
+
if ref_sr != S3_SR:
|
|
149
|
+
ref_wav_16 = get_resampler(ref_sr, S3_SR, device)(ref_wav)
|
|
150
|
+
|
|
151
|
+
# Speaker embedding
|
|
152
|
+
ref_x_vector = self.speaker_encoder.inference(ref_wav_16.to(dtype=self.dtype))
|
|
153
|
+
|
|
154
|
+
# Tokenize 16khz reference
|
|
155
|
+
ref_speech_tokens, ref_speech_token_lens = self.tokenizer(ref_wav_16.float())
|
|
156
|
+
|
|
157
|
+
# Make sure mel_len = 2 * stoken_len (happens when the input is not padded to multiple of 40ms)
|
|
158
|
+
if ref_mels_24.shape[1] != 2 * ref_speech_tokens.shape[1]:
|
|
159
|
+
logging.warning(
|
|
160
|
+
"Reference mel length is not equal to 2 * reference token length.\n"
|
|
161
|
+
)
|
|
162
|
+
ref_speech_tokens = ref_speech_tokens[:, :ref_mels_24.shape[1] // 2]
|
|
163
|
+
ref_speech_token_lens[0] = ref_speech_tokens.shape[1]
|
|
164
|
+
|
|
165
|
+
return dict(
|
|
166
|
+
prompt_token=ref_speech_tokens.to(device),
|
|
167
|
+
prompt_token_len=ref_speech_token_lens,
|
|
168
|
+
prompt_feat=ref_mels_24,
|
|
169
|
+
prompt_feat_len=ref_mels_24_len,
|
|
170
|
+
embedding=ref_x_vector,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def forward(
|
|
174
|
+
self,
|
|
175
|
+
speech_tokens: torch.LongTensor,
|
|
176
|
+
# locally-computed ref embedding (mutex with ref_dict)
|
|
177
|
+
ref_wav: Optional[torch.Tensor],
|
|
178
|
+
ref_sr: Optional[int],
|
|
179
|
+
# pre-computed ref embedding (prod API)
|
|
180
|
+
ref_dict: Optional[dict] = None,
|
|
181
|
+
n_cfm_timesteps = None,
|
|
182
|
+
finalize: bool = False,
|
|
183
|
+
speech_token_lens=None,
|
|
184
|
+
noised_mels=None,
|
|
185
|
+
):
|
|
186
|
+
"""
|
|
187
|
+
Generate waveforms from S3 speech tokens and a reference waveform, which the speaker timbre is inferred from.
|
|
188
|
+
|
|
189
|
+
NOTE:
|
|
190
|
+
- The speaker encoder accepts 16 kHz waveform.
|
|
191
|
+
- S3TokenizerV2 accepts 16 kHz waveform.
|
|
192
|
+
- The mel-spectrogram for the reference assumes 24 kHz input signal.
|
|
193
|
+
- This function is designed for batch_size=1 only.
|
|
194
|
+
|
|
195
|
+
Args
|
|
196
|
+
----
|
|
197
|
+
- `speech_tokens`: S3 speech tokens [B=1, T]
|
|
198
|
+
- `ref_wav`: reference waveform (`torch.Tensor` with shape=[B=1, T])
|
|
199
|
+
- `ref_sr`: reference sample rate
|
|
200
|
+
- `finalize`: whether streaming is finished or not. Note that if False, the last 3 tokens will be ignored.
|
|
201
|
+
"""
|
|
202
|
+
assert (ref_wav is None) ^ (ref_dict is None), f"Must provide exactly one of ref_wav or ref_dict (got {ref_wav} and {ref_dict})"
|
|
203
|
+
|
|
204
|
+
if ref_dict is None:
|
|
205
|
+
ref_dict = self.embed_ref(ref_wav, ref_sr)
|
|
206
|
+
else:
|
|
207
|
+
# type/device casting (all values will be numpy if it's from a prod API call)
|
|
208
|
+
for rk in list(ref_dict):
|
|
209
|
+
if isinstance(ref_dict[rk], np.ndarray):
|
|
210
|
+
ref_dict[rk] = torch.from_numpy(ref_dict[rk])
|
|
211
|
+
if torch.is_tensor(ref_dict[rk]):
|
|
212
|
+
ref_dict[rk] = ref_dict[rk].to(device=self.device, dtype=self.dtype)
|
|
213
|
+
|
|
214
|
+
speech_tokens = torch.atleast_2d(speech_tokens)
|
|
215
|
+
|
|
216
|
+
# backcompat
|
|
217
|
+
if speech_token_lens is None:
|
|
218
|
+
speech_token_lens = torch.LongTensor([st.size(-1) for st in speech_tokens]).to(self.device)
|
|
219
|
+
|
|
220
|
+
output_mels, _ = self.flow.inference(
|
|
221
|
+
token=speech_tokens,
|
|
222
|
+
token_len=speech_token_lens,
|
|
223
|
+
finalize=finalize,
|
|
224
|
+
noised_mels=noised_mels,
|
|
225
|
+
n_timesteps=n_cfm_timesteps,
|
|
226
|
+
meanflow=self.meanflow,
|
|
227
|
+
**ref_dict,
|
|
228
|
+
)
|
|
229
|
+
return output_mels
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class S3Token2Wav(S3Token2Mel):
|
|
233
|
+
"""
|
|
234
|
+
The decoder of S3Gen is a concat of token-to-mel (CFM) and a mel-to-waveform (HiFiGAN) modules.
|
|
235
|
+
|
|
236
|
+
TODO: make these modules configurable?
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
ignore_state_dict_missing = ("tokenizer._mel_filters", "tokenizer.window")
|
|
240
|
+
|
|
241
|
+
def __init__(self, meanflow=False):
|
|
242
|
+
super().__init__(meanflow)
|
|
243
|
+
|
|
244
|
+
f0_predictor = ConvRNNF0Predictor()
|
|
245
|
+
self.mel2wav = HiFTGenerator(
|
|
246
|
+
sampling_rate=S3GEN_SR,
|
|
247
|
+
upsample_rates=[8, 5, 3],
|
|
248
|
+
upsample_kernel_sizes=[16, 11, 7],
|
|
249
|
+
source_resblock_kernel_sizes=[7, 7, 11],
|
|
250
|
+
source_resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
|
251
|
+
f0_predictor=f0_predictor,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
# silence out a few ms and fade audio in to reduce artifacts
|
|
255
|
+
n_trim = S3GEN_SR // 50 # 20ms = half of a frame
|
|
256
|
+
trim_fade = torch.zeros(2 * n_trim)
|
|
257
|
+
trim_fade[n_trim:] = (torch.cos(torch.linspace(torch.pi, 0, n_trim)) + 1) / 2
|
|
258
|
+
self.register_buffer("trim_fade", trim_fade, persistent=False) # (buffers get automatic device casting)
|
|
259
|
+
self.estimator_dtype = "fp32"
|
|
260
|
+
|
|
261
|
+
def forward(
|
|
262
|
+
self,
|
|
263
|
+
speech_tokens,
|
|
264
|
+
# locally-computed ref embedding (mutex with ref_dict)
|
|
265
|
+
ref_wav: Optional[torch.Tensor],
|
|
266
|
+
ref_sr: Optional[int],
|
|
267
|
+
# pre-computed ref embedding (prod API)
|
|
268
|
+
ref_dict: Optional[dict] = None,
|
|
269
|
+
finalize: bool = False,
|
|
270
|
+
speech_token_lens=None,
|
|
271
|
+
skip_vocoder=False,
|
|
272
|
+
n_cfm_timesteps=None,
|
|
273
|
+
noised_mels=None,
|
|
274
|
+
|
|
275
|
+
):
|
|
276
|
+
"""
|
|
277
|
+
Generate waveforms from S3 speech tokens and a reference waveform, which the speaker timbre is inferred from.
|
|
278
|
+
NOTE: used for sync synthesis only. Please use `S3GenStreamer` for streaming synthesis.
|
|
279
|
+
"""
|
|
280
|
+
output_mels = super().forward(
|
|
281
|
+
speech_tokens, speech_token_lens=speech_token_lens, ref_wav=ref_wav,
|
|
282
|
+
ref_sr=ref_sr, ref_dict=ref_dict, finalize=finalize,
|
|
283
|
+
n_cfm_timesteps=n_cfm_timesteps, noised_mels=noised_mels,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
if skip_vocoder:
|
|
287
|
+
return output_mels
|
|
288
|
+
|
|
289
|
+
# TODO jrm: ignoring the speed control (mel interpolation) and the HiFTGAN caching mechanisms for now.
|
|
290
|
+
hift_cache_source = torch.zeros(1, 1, 0).to(self.device)
|
|
291
|
+
|
|
292
|
+
output_wavs, *_ = self.mel2wav.inference(speech_feat=output_mels, cache_source=hift_cache_source)
|
|
293
|
+
|
|
294
|
+
if not self.training:
|
|
295
|
+
# NOTE: ad-hoc method to reduce "spillover" from the reference clip.
|
|
296
|
+
output_wavs[:, :len(self.trim_fade)] *= self.trim_fade
|
|
297
|
+
|
|
298
|
+
return output_wavs
|
|
299
|
+
|
|
300
|
+
@torch.inference_mode()
|
|
301
|
+
def flow_inference(
|
|
302
|
+
self,
|
|
303
|
+
speech_tokens,
|
|
304
|
+
# locally-computed ref embedding (mutex with ref_dict)
|
|
305
|
+
ref_wav: Optional[torch.Tensor] = None,
|
|
306
|
+
ref_sr: Optional[int] = None,
|
|
307
|
+
# pre-computed ref embedding (prod API)
|
|
308
|
+
ref_dict: Optional[dict] = None,
|
|
309
|
+
n_cfm_timesteps = None,
|
|
310
|
+
finalize: bool = False,
|
|
311
|
+
speech_token_lens=None,
|
|
312
|
+
):
|
|
313
|
+
n_cfm_timesteps = n_cfm_timesteps or (2 if self.meanflow else 10)
|
|
314
|
+
noise = None
|
|
315
|
+
if self.meanflow:
|
|
316
|
+
noise = torch.randn(1, 80, speech_tokens.size(-1) * 2, dtype=self.dtype, device=self.device)
|
|
317
|
+
output_mels = super().forward(
|
|
318
|
+
speech_tokens, speech_token_lens=speech_token_lens, ref_wav=ref_wav, ref_sr=ref_sr, ref_dict=ref_dict,
|
|
319
|
+
n_cfm_timesteps=n_cfm_timesteps, finalize=finalize, noised_mels=noise,
|
|
320
|
+
)
|
|
321
|
+
return output_mels
|
|
322
|
+
|
|
323
|
+
@torch.inference_mode()
|
|
324
|
+
def hift_inference(self, speech_feat, cache_source: torch.Tensor = None):
|
|
325
|
+
if cache_source is None:
|
|
326
|
+
cache_source = torch.zeros(1, 1, 0).to(device=self.device, dtype=self.dtype)
|
|
327
|
+
return self.mel2wav.inference(speech_feat=speech_feat, cache_source=cache_source)
|
|
328
|
+
|
|
329
|
+
@torch.inference_mode()
|
|
330
|
+
def inference(
|
|
331
|
+
self,
|
|
332
|
+
speech_tokens,
|
|
333
|
+
# locally-computed ref embedding (mutex with ref_dict)
|
|
334
|
+
ref_wav: Optional[torch.Tensor] = None,
|
|
335
|
+
ref_sr: Optional[int] = None,
|
|
336
|
+
# pre-computed ref embedding (prod API)
|
|
337
|
+
ref_dict: Optional[dict] = None,
|
|
338
|
+
# left as a kwarg because this can change input/output size ratio
|
|
339
|
+
drop_invalid_tokens=True,
|
|
340
|
+
n_cfm_timesteps=None,
|
|
341
|
+
speech_token_lens=None,
|
|
342
|
+
):
|
|
343
|
+
# hallucination prevention, drop special tokens
|
|
344
|
+
# if drop_invalid_tokens:
|
|
345
|
+
# speech_tokens, speech_token_lens = drop_invalid(speech_tokens, pad=S3_QUIET_PAD)
|
|
346
|
+
|
|
347
|
+
output_mels = self.flow_inference(
|
|
348
|
+
speech_tokens,
|
|
349
|
+
speech_token_lens=speech_token_lens,
|
|
350
|
+
ref_wav=ref_wav,
|
|
351
|
+
ref_sr=ref_sr,
|
|
352
|
+
ref_dict=ref_dict,
|
|
353
|
+
n_cfm_timesteps=n_cfm_timesteps,
|
|
354
|
+
finalize=True,
|
|
355
|
+
)
|
|
356
|
+
output_mels = output_mels.to(dtype=self.dtype) # FIXME (fp16 mode) is this still needed?
|
|
357
|
+
output_wavs, output_sources = self.hift_inference(output_mels, None)
|
|
358
|
+
|
|
359
|
+
# NOTE: ad-hoc method to reduce "spillover" from the reference clip.
|
|
360
|
+
output_wavs[:, :len(self.trim_fade)] *= self.trim_fade
|
|
361
|
+
|
|
362
|
+
return output_wavs, output_sources
|
|
File without changes
|