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
chatterbox/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
try:
|
|
2
|
+
from importlib.metadata import version
|
|
3
|
+
except ImportError:
|
|
4
|
+
from importlib_metadata import version # For Python <3.8
|
|
5
|
+
|
|
6
|
+
# FORK: upstream reads version("chatterbox-tts"). This distribution is named
|
|
7
|
+
# videopython-chatterbox, so that lookup raises PackageNotFoundError at import.
|
|
8
|
+
# This is the only line that differs from upstream 0.1.7.
|
|
9
|
+
__version__ = version("videopython-chatterbox")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
from .tts import ChatterboxTTS
|
|
13
|
+
from .vc import ChatterboxVC
|
|
14
|
+
from .mtl_tts import ChatterboxMultilingualTTS, SUPPORTED_LANGUAGES
|
|
File without changes
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
|
|
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
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
import torch.nn.functional as F
|
|
17
|
+
from einops import pack, rearrange, repeat
|
|
18
|
+
|
|
19
|
+
from .utils.mask import add_optional_chunk_mask
|
|
20
|
+
from .matcha.decoder import SinusoidalPosEmb, Block1D, ResnetBlock1D, Downsample1D, \
|
|
21
|
+
TimestepEmbedding, Upsample1D
|
|
22
|
+
from .matcha.transformer import BasicTransformerBlock
|
|
23
|
+
from .utils.intmeanflow import get_intmeanflow_time_mixer
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
|
27
|
+
assert mask.dtype == torch.bool
|
|
28
|
+
assert dtype in [torch.float32, torch.bfloat16, torch.float16]
|
|
29
|
+
mask = mask.to(dtype)
|
|
30
|
+
# attention mask bias
|
|
31
|
+
# NOTE(Mddct): torch.finfo jit issues
|
|
32
|
+
# chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
|
|
33
|
+
mask = (1.0 - mask) * -1.0e+10
|
|
34
|
+
return mask
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Transpose(torch.nn.Module):
|
|
39
|
+
def __init__(self, dim0: int, dim1: int):
|
|
40
|
+
super().__init__()
|
|
41
|
+
self.dim0 = dim0
|
|
42
|
+
self.dim1 = dim1
|
|
43
|
+
|
|
44
|
+
def forward(self, x: torch.Tensor):
|
|
45
|
+
x = torch.transpose(x, self.dim0, self.dim1)
|
|
46
|
+
return x
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CausalBlock1D(Block1D):
|
|
50
|
+
def __init__(self, dim: int, dim_out: int):
|
|
51
|
+
super(CausalBlock1D, self).__init__(dim, dim_out)
|
|
52
|
+
self.block = torch.nn.Sequential(
|
|
53
|
+
CausalConv1d(dim, dim_out, 3),
|
|
54
|
+
Transpose(1, 2),
|
|
55
|
+
nn.LayerNorm(dim_out),
|
|
56
|
+
Transpose(1, 2),
|
|
57
|
+
nn.Mish(),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def forward(self, x: torch.Tensor, mask: torch.Tensor):
|
|
61
|
+
output = self.block(x * mask)
|
|
62
|
+
return output * mask
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class CausalResnetBlock1D(ResnetBlock1D):
|
|
66
|
+
def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
|
|
67
|
+
super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
|
|
68
|
+
self.block1 = CausalBlock1D(dim, dim_out)
|
|
69
|
+
self.block2 = CausalBlock1D(dim_out, dim_out)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class CausalConv1d(torch.nn.Conv1d):
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
in_channels: int,
|
|
76
|
+
out_channels: int,
|
|
77
|
+
kernel_size: int,
|
|
78
|
+
stride: int = 1,
|
|
79
|
+
dilation: int = 1,
|
|
80
|
+
groups: int = 1,
|
|
81
|
+
bias: bool = True,
|
|
82
|
+
padding_mode: str = 'zeros',
|
|
83
|
+
device=None,
|
|
84
|
+
dtype=None
|
|
85
|
+
) -> None:
|
|
86
|
+
super(CausalConv1d, self).__init__(in_channels, out_channels,
|
|
87
|
+
kernel_size, stride,
|
|
88
|
+
padding=0, dilation=dilation,
|
|
89
|
+
groups=groups, bias=bias,
|
|
90
|
+
padding_mode=padding_mode,
|
|
91
|
+
device=device, dtype=dtype)
|
|
92
|
+
assert stride == 1
|
|
93
|
+
self.causal_padding = (kernel_size - 1, 0)
|
|
94
|
+
|
|
95
|
+
def forward(self, x: torch.Tensor):
|
|
96
|
+
x = F.pad(x, self.causal_padding)
|
|
97
|
+
x = super(CausalConv1d, self).forward(x)
|
|
98
|
+
return x
|
|
99
|
+
class ConditionalDecoder(nn.Module):
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
in_channels=320,
|
|
103
|
+
out_channels=80,
|
|
104
|
+
causal=True,
|
|
105
|
+
channels=[256],
|
|
106
|
+
dropout=0.0,
|
|
107
|
+
attention_head_dim=64,
|
|
108
|
+
n_blocks=4,
|
|
109
|
+
num_mid_blocks=12,
|
|
110
|
+
num_heads=8,
|
|
111
|
+
act_fn="gelu",
|
|
112
|
+
meanflow=False,
|
|
113
|
+
):
|
|
114
|
+
"""
|
|
115
|
+
This decoder requires an input with the same shape of the target. So, if your text content
|
|
116
|
+
is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
|
|
117
|
+
"""
|
|
118
|
+
super().__init__()
|
|
119
|
+
channels = tuple(channels)
|
|
120
|
+
self.meanflow = meanflow
|
|
121
|
+
self.in_channels = in_channels
|
|
122
|
+
self.out_channels = out_channels
|
|
123
|
+
self.causal = causal
|
|
124
|
+
self.time_embeddings = SinusoidalPosEmb(in_channels)
|
|
125
|
+
time_embed_dim = channels[0] * 4
|
|
126
|
+
self.time_mlp = TimestepEmbedding(
|
|
127
|
+
in_channels=in_channels,
|
|
128
|
+
time_embed_dim=time_embed_dim,
|
|
129
|
+
act_fn="silu",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
self.down_blocks = nn.ModuleList([])
|
|
133
|
+
self.mid_blocks = nn.ModuleList([])
|
|
134
|
+
self.up_blocks = nn.ModuleList([])
|
|
135
|
+
|
|
136
|
+
# NOTE jrm: `static_chunk_size` is missing?
|
|
137
|
+
self.static_chunk_size = 0
|
|
138
|
+
|
|
139
|
+
output_channel = in_channels
|
|
140
|
+
for i in range(len(channels)): # pylint: disable=consider-using-enumerate
|
|
141
|
+
input_channel = output_channel
|
|
142
|
+
output_channel = channels[i]
|
|
143
|
+
is_last = i == len(channels) - 1
|
|
144
|
+
resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) if self.causal else \
|
|
145
|
+
ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
|
|
146
|
+
transformer_blocks = nn.ModuleList(
|
|
147
|
+
[
|
|
148
|
+
BasicTransformerBlock(
|
|
149
|
+
dim=output_channel,
|
|
150
|
+
num_attention_heads=num_heads,
|
|
151
|
+
attention_head_dim=attention_head_dim,
|
|
152
|
+
dropout=dropout,
|
|
153
|
+
activation_fn=act_fn,
|
|
154
|
+
)
|
|
155
|
+
for _ in range(n_blocks)
|
|
156
|
+
]
|
|
157
|
+
)
|
|
158
|
+
downsample = (
|
|
159
|
+
Downsample1D(output_channel) if not is_last else
|
|
160
|
+
CausalConv1d(output_channel, output_channel, 3) if self.causal else nn.Conv1d(output_channel, output_channel, 3, padding=1)
|
|
161
|
+
)
|
|
162
|
+
self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
|
|
163
|
+
|
|
164
|
+
for _ in range(num_mid_blocks):
|
|
165
|
+
input_channel = channels[-1]
|
|
166
|
+
out_channels = channels[-1]
|
|
167
|
+
resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) if self.causal else \
|
|
168
|
+
ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
|
|
169
|
+
|
|
170
|
+
transformer_blocks = nn.ModuleList(
|
|
171
|
+
[
|
|
172
|
+
BasicTransformerBlock(
|
|
173
|
+
dim=output_channel,
|
|
174
|
+
num_attention_heads=num_heads,
|
|
175
|
+
attention_head_dim=attention_head_dim,
|
|
176
|
+
dropout=dropout,
|
|
177
|
+
activation_fn=act_fn,
|
|
178
|
+
)
|
|
179
|
+
for _ in range(n_blocks)
|
|
180
|
+
]
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
|
|
184
|
+
|
|
185
|
+
channels = channels[::-1] + (channels[0],)
|
|
186
|
+
for i in range(len(channels) - 1):
|
|
187
|
+
input_channel = channels[i] * 2
|
|
188
|
+
output_channel = channels[i + 1]
|
|
189
|
+
is_last = i == len(channels) - 2
|
|
190
|
+
resnet = CausalResnetBlock1D(
|
|
191
|
+
dim=input_channel,
|
|
192
|
+
dim_out=output_channel,
|
|
193
|
+
time_emb_dim=time_embed_dim,
|
|
194
|
+
) if self.causal else ResnetBlock1D(
|
|
195
|
+
dim=input_channel,
|
|
196
|
+
dim_out=output_channel,
|
|
197
|
+
time_emb_dim=time_embed_dim,
|
|
198
|
+
)
|
|
199
|
+
transformer_blocks = nn.ModuleList(
|
|
200
|
+
[
|
|
201
|
+
BasicTransformerBlock(
|
|
202
|
+
dim=output_channel,
|
|
203
|
+
num_attention_heads=num_heads,
|
|
204
|
+
attention_head_dim=attention_head_dim,
|
|
205
|
+
dropout=dropout,
|
|
206
|
+
activation_fn=act_fn,
|
|
207
|
+
)
|
|
208
|
+
for _ in range(n_blocks)
|
|
209
|
+
]
|
|
210
|
+
)
|
|
211
|
+
upsample = (
|
|
212
|
+
Upsample1D(output_channel, use_conv_transpose=True)
|
|
213
|
+
if not is_last
|
|
214
|
+
else CausalConv1d(output_channel, output_channel, 3) if self.causal else nn.Conv1d(output_channel, output_channel, 3, padding=1)
|
|
215
|
+
)
|
|
216
|
+
self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
|
|
217
|
+
self.final_block = CausalBlock1D(channels[-1], channels[-1]) if self.causal else Block1D(channels[-1], channels[-1])
|
|
218
|
+
self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
|
|
219
|
+
self.initialize_weights()
|
|
220
|
+
self.time_embed_mixer = None
|
|
221
|
+
if self.meanflow:
|
|
222
|
+
self.time_embed_mixer = get_intmeanflow_time_mixer(time_embed_dim)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def dtype(self):
|
|
227
|
+
return self.final_proj.weight.dtype
|
|
228
|
+
|
|
229
|
+
def initialize_weights(self):
|
|
230
|
+
for m in self.modules():
|
|
231
|
+
if isinstance(m, nn.Conv1d):
|
|
232
|
+
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
|
|
233
|
+
if m.bias is not None:
|
|
234
|
+
nn.init.constant_(m.bias, 0)
|
|
235
|
+
elif isinstance(m, nn.GroupNorm):
|
|
236
|
+
nn.init.constant_(m.weight, 1)
|
|
237
|
+
nn.init.constant_(m.bias, 0)
|
|
238
|
+
elif isinstance(m, nn.Linear):
|
|
239
|
+
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
|
|
240
|
+
if m.bias is not None:
|
|
241
|
+
nn.init.constant_(m.bias, 0)
|
|
242
|
+
|
|
243
|
+
def forward(self, x, mask, mu, t, spks=None, cond=None, r=None):
|
|
244
|
+
"""Forward pass of the UNet1DConditional model.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
x: (B, 80, T)
|
|
248
|
+
mask (_type_)
|
|
249
|
+
t (_type_): shape (batch_size)
|
|
250
|
+
spks (_type_, optional) Defaults to None.
|
|
251
|
+
cond (_type_, optional)
|
|
252
|
+
r: end time for meanflow mode (shape (1,) tensor)
|
|
253
|
+
|
|
254
|
+
Raises:
|
|
255
|
+
ValueError: _description_
|
|
256
|
+
ValueError: _description_
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
_type_: _description_
|
|
260
|
+
"""
|
|
261
|
+
t = self.time_embeddings(t).to(t.dtype)
|
|
262
|
+
t = self.time_mlp(t)
|
|
263
|
+
|
|
264
|
+
if self.meanflow:
|
|
265
|
+
r = self.time_embeddings(r).to(t.dtype)
|
|
266
|
+
r = self.time_mlp(r)
|
|
267
|
+
concat_embed = torch.cat([t, r], dim=1)
|
|
268
|
+
t = self.time_embed_mixer(concat_embed)
|
|
269
|
+
|
|
270
|
+
x = pack([x, mu], "b * t")[0]
|
|
271
|
+
|
|
272
|
+
if spks is not None:
|
|
273
|
+
spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
|
|
274
|
+
x = pack([x, spks], "b * t")[0]
|
|
275
|
+
if cond is not None:
|
|
276
|
+
x = pack([x, cond], "b * t")[0]
|
|
277
|
+
|
|
278
|
+
hiddens = []
|
|
279
|
+
masks = [mask]
|
|
280
|
+
for resnet, transformer_blocks, downsample in self.down_blocks:
|
|
281
|
+
mask_down = masks[-1]
|
|
282
|
+
x = resnet(x, mask_down, t)
|
|
283
|
+
x = rearrange(x, "b c t -> b t c").contiguous()
|
|
284
|
+
# attn_mask = torch.matmul(mask_down.transpose(1, 2).contiguous(), mask_down)
|
|
285
|
+
attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, -1)
|
|
286
|
+
attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
|
|
287
|
+
for transformer_block in transformer_blocks:
|
|
288
|
+
x = transformer_block(
|
|
289
|
+
hidden_states=x,
|
|
290
|
+
attention_mask=attn_mask,
|
|
291
|
+
timestep=t,
|
|
292
|
+
)
|
|
293
|
+
x = rearrange(x, "b t c -> b c t").contiguous()
|
|
294
|
+
hiddens.append(x) # Save hidden states for skip connections
|
|
295
|
+
x = downsample(x * mask_down)
|
|
296
|
+
masks.append(mask_down[:, :, ::2])
|
|
297
|
+
masks = masks[:-1]
|
|
298
|
+
mask_mid = masks[-1]
|
|
299
|
+
|
|
300
|
+
for resnet, transformer_blocks in self.mid_blocks:
|
|
301
|
+
x = resnet(x, mask_mid, t)
|
|
302
|
+
x = rearrange(x, "b c t -> b t c").contiguous()
|
|
303
|
+
# attn_mask = torch.matmul(mask_mid.transpose(1, 2).contiguous(), mask_mid)
|
|
304
|
+
attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, -1)
|
|
305
|
+
attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
|
|
306
|
+
for transformer_block in transformer_blocks:
|
|
307
|
+
x = transformer_block(
|
|
308
|
+
hidden_states=x,
|
|
309
|
+
attention_mask=attn_mask,
|
|
310
|
+
timestep=t,
|
|
311
|
+
)
|
|
312
|
+
x = rearrange(x, "b t c -> b c t").contiguous()
|
|
313
|
+
|
|
314
|
+
for resnet, transformer_blocks, upsample in self.up_blocks:
|
|
315
|
+
mask_up = masks.pop()
|
|
316
|
+
skip = hiddens.pop()
|
|
317
|
+
x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
|
|
318
|
+
x = resnet(x, mask_up, t)
|
|
319
|
+
x = rearrange(x, "b c t -> b t c").contiguous()
|
|
320
|
+
# attn_mask = torch.matmul(mask_up.transpose(1, 2).contiguous(), mask_up)
|
|
321
|
+
attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, -1)
|
|
322
|
+
attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
|
|
323
|
+
for transformer_block in transformer_blocks:
|
|
324
|
+
x = transformer_block(
|
|
325
|
+
hidden_states=x,
|
|
326
|
+
attention_mask=attn_mask,
|
|
327
|
+
timestep=t,
|
|
328
|
+
)
|
|
329
|
+
x = rearrange(x, "b t c -> b c t").contiguous()
|
|
330
|
+
x = upsample(x * mask_up)
|
|
331
|
+
x = self.final_block(x, mask_up)
|
|
332
|
+
output = self.final_proj(x * mask_up)
|
|
333
|
+
return output * mask
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Kai Hu)
|
|
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
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
from torch.nn.utils.parametrizations import weight_norm
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConvRNNF0Predictor(nn.Module):
|
|
20
|
+
def __init__(self,
|
|
21
|
+
num_class: int = 1,
|
|
22
|
+
in_channels: int = 80,
|
|
23
|
+
cond_channels: int = 512
|
|
24
|
+
):
|
|
25
|
+
super().__init__()
|
|
26
|
+
|
|
27
|
+
self.num_class = num_class
|
|
28
|
+
self.condnet = nn.Sequential(
|
|
29
|
+
weight_norm(
|
|
30
|
+
nn.Conv1d(in_channels, cond_channels, kernel_size=3, padding=1)
|
|
31
|
+
),
|
|
32
|
+
nn.ELU(),
|
|
33
|
+
weight_norm(
|
|
34
|
+
nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
|
|
35
|
+
),
|
|
36
|
+
nn.ELU(),
|
|
37
|
+
weight_norm(
|
|
38
|
+
nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
|
|
39
|
+
),
|
|
40
|
+
nn.ELU(),
|
|
41
|
+
weight_norm(
|
|
42
|
+
nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
|
|
43
|
+
),
|
|
44
|
+
nn.ELU(),
|
|
45
|
+
weight_norm(
|
|
46
|
+
nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
|
|
47
|
+
),
|
|
48
|
+
nn.ELU(),
|
|
49
|
+
)
|
|
50
|
+
self.classifier = nn.Linear(in_features=cond_channels, out_features=self.num_class)
|
|
51
|
+
|
|
52
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
53
|
+
x = self.condnet(x)
|
|
54
|
+
x = x.transpose(1, 2)
|
|
55
|
+
return torch.abs(self.classifier(x).squeeze(-1))
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
|
|
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
|
+
import logging
|
|
15
|
+
import random
|
|
16
|
+
from typing import Dict, Optional
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
import torch
|
|
20
|
+
import torch.nn as nn
|
|
21
|
+
from torch.nn import functional as F
|
|
22
|
+
from .utils.mask import make_pad_mask
|
|
23
|
+
from .configs import CFM_PARAMS
|
|
24
|
+
from omegaconf import DictConfig
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _repeat_batch_dim(tnsr, B, ndim):
|
|
31
|
+
"repeat batch dimension if it's equal to 1"
|
|
32
|
+
if tnsr is not None:
|
|
33
|
+
# add missing batch dim if needed
|
|
34
|
+
while tnsr.ndim < ndim:
|
|
35
|
+
tnsr = tnsr[None]
|
|
36
|
+
# repeat batch dim as needed
|
|
37
|
+
if B > 1 and tnsr.size(0) == 1:
|
|
38
|
+
tnsr = tnsr.repeat(B, *([1] * (ndim - 1)))
|
|
39
|
+
assert tnsr.ndim == ndim, f"Expected {ndim=}, got {tnsr.ndim=}"
|
|
40
|
+
return tnsr
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CausalMaskedDiffWithXvec(torch.nn.Module):
|
|
44
|
+
def __init__(self,
|
|
45
|
+
input_size: int = 512,
|
|
46
|
+
output_size: int = 80,
|
|
47
|
+
spk_embed_dim: int = 192,
|
|
48
|
+
output_type: str = "mel",
|
|
49
|
+
vocab_size: int = 6561,
|
|
50
|
+
input_frame_rate: int = 25,
|
|
51
|
+
only_mask_loss: bool = True,
|
|
52
|
+
token_mel_ratio: int = 2,
|
|
53
|
+
pre_lookahead_len: int = 3,
|
|
54
|
+
encoder: torch.nn.Module = None,
|
|
55
|
+
decoder: torch.nn.Module = None,
|
|
56
|
+
decoder_conf: Dict = {'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,
|
|
57
|
+
'cfm_params': DictConfig(
|
|
58
|
+
{'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine',
|
|
59
|
+
'training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7,
|
|
60
|
+
'reg_loss_type': 'l1'}),
|
|
61
|
+
'decoder_params': {'channels': [256, 256], 'dropout': 0.0,
|
|
62
|
+
'attention_head_dim': 64,
|
|
63
|
+
'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8,
|
|
64
|
+
'act_fn': 'gelu'}},
|
|
65
|
+
mel_feat_conf: Dict = {'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,
|
|
66
|
+
'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000}):
|
|
67
|
+
super().__init__()
|
|
68
|
+
self.input_size = input_size
|
|
69
|
+
self.output_size = output_size
|
|
70
|
+
self.decoder_conf = decoder_conf
|
|
71
|
+
self.mel_feat_conf = mel_feat_conf
|
|
72
|
+
self.vocab_size = vocab_size
|
|
73
|
+
self.output_type = output_type
|
|
74
|
+
self.input_frame_rate = input_frame_rate
|
|
75
|
+
logging.info(f"input frame rate={self.input_frame_rate}")
|
|
76
|
+
self.input_embedding = nn.Embedding(vocab_size, input_size)
|
|
77
|
+
self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, output_size)
|
|
78
|
+
self.encoder = encoder
|
|
79
|
+
self.encoder_proj = torch.nn.Linear(self.encoder.output_size(), output_size)
|
|
80
|
+
self.decoder = decoder
|
|
81
|
+
self.only_mask_loss = only_mask_loss
|
|
82
|
+
self.token_mel_ratio = token_mel_ratio
|
|
83
|
+
self.pre_lookahead_len = pre_lookahead_len
|
|
84
|
+
|
|
85
|
+
# NOTE: copied in from cosyvoice repo
|
|
86
|
+
def compute_loss(
|
|
87
|
+
self,
|
|
88
|
+
batch: dict,
|
|
89
|
+
device: torch.device,
|
|
90
|
+
) -> Dict[str, Optional[torch.Tensor]]:
|
|
91
|
+
token = batch['speech_token'].to(device)
|
|
92
|
+
token_len = batch['speech_token_len'].to(device)
|
|
93
|
+
feat = batch['speech_feat'].to(device) # (B, 80, T)
|
|
94
|
+
feat_len = batch['speech_feat_len'].to(device)
|
|
95
|
+
embedding = batch['embedding'].to(device)
|
|
96
|
+
|
|
97
|
+
# NOTE unified training, static_chunk_size > 0 or = 0
|
|
98
|
+
# streaming = True if random.random() < 0.5 else False
|
|
99
|
+
|
|
100
|
+
# xvec projection
|
|
101
|
+
embedding = F.normalize(embedding, dim=1)
|
|
102
|
+
embedding = self.spk_embed_affine_layer(embedding)
|
|
103
|
+
|
|
104
|
+
# concat text and prompt_text
|
|
105
|
+
mask = (~make_pad_mask(token_len)).float().unsqueeze(-1).to(device) # (B, T, 1)
|
|
106
|
+
token = self.input_embedding(torch.clamp(token, min=0)) * mask # (B, T, emb)
|
|
107
|
+
|
|
108
|
+
# text encode
|
|
109
|
+
h, h_lengths = self.encoder(token, token_len) # (B, T, C) -> (B, 2T, C)
|
|
110
|
+
h = self.encoder_proj(h)
|
|
111
|
+
|
|
112
|
+
# get conditions
|
|
113
|
+
conds = torch.zeros(feat.shape, device=token.device)
|
|
114
|
+
for i, j in enumerate(feat_len):
|
|
115
|
+
if random.random() < 0.5:
|
|
116
|
+
continue
|
|
117
|
+
index = random.randint(0, int(0.3 * j))
|
|
118
|
+
conds[i, :, :index] = feat[i, :, :index]
|
|
119
|
+
|
|
120
|
+
mask = (~make_pad_mask(h_lengths.sum(dim=-1).squeeze(dim=1))).to(h)
|
|
121
|
+
loss, _ = self.decoder.compute_loss(
|
|
122
|
+
feat.contiguous(),
|
|
123
|
+
mask.unsqueeze(1),
|
|
124
|
+
h.transpose(1, 2).contiguous(),
|
|
125
|
+
embedding,
|
|
126
|
+
cond=conds,
|
|
127
|
+
# streaming=streaming,
|
|
128
|
+
)
|
|
129
|
+
return {'loss': loss}
|
|
130
|
+
|
|
131
|
+
@torch.inference_mode()
|
|
132
|
+
def inference(self,
|
|
133
|
+
token,
|
|
134
|
+
token_len,
|
|
135
|
+
prompt_token,
|
|
136
|
+
prompt_token_len,
|
|
137
|
+
prompt_feat,
|
|
138
|
+
prompt_feat_len,
|
|
139
|
+
embedding,
|
|
140
|
+
finalize,
|
|
141
|
+
n_timesteps=10,
|
|
142
|
+
noised_mels=None,
|
|
143
|
+
meanflow=False):
|
|
144
|
+
# token: (B, n_toks)
|
|
145
|
+
# token_len: (B,)
|
|
146
|
+
B = token.size(0)
|
|
147
|
+
|
|
148
|
+
# xvec projection
|
|
149
|
+
embedding = torch.atleast_2d(embedding)
|
|
150
|
+
embedding = F.normalize(embedding, dim=1)
|
|
151
|
+
embedding = self.spk_embed_affine_layer(embedding) # (1 or B, emb_dim)
|
|
152
|
+
|
|
153
|
+
# adjust shapes (batching logic)
|
|
154
|
+
prompt_token = _repeat_batch_dim(prompt_token, B, ndim=2) # (B, n_prompt)
|
|
155
|
+
prompt_token_len = _repeat_batch_dim(prompt_token_len, B, ndim=1) # (B,)
|
|
156
|
+
prompt_feat = _repeat_batch_dim(prompt_feat, B, ndim=3) # (B, n_feat, feat_dim=80)
|
|
157
|
+
prompt_feat_len = _repeat_batch_dim(prompt_feat_len, B, ndim=1) # (B,) or None
|
|
158
|
+
embedding = _repeat_batch_dim(embedding, B, ndim=2) # (B, emb_dim)
|
|
159
|
+
|
|
160
|
+
# concat text and prompt_text
|
|
161
|
+
token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
|
|
162
|
+
mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
|
|
163
|
+
|
|
164
|
+
if (token >= self.vocab_size).any():
|
|
165
|
+
logger.error(f"{token.max()}>{self.vocab_size}\n out-of-range special tokens found in flow, fix inputs!")
|
|
166
|
+
token = self.input_embedding(token.long()) * mask
|
|
167
|
+
|
|
168
|
+
# text encode
|
|
169
|
+
h, h_masks = self.encoder(token, token_len)
|
|
170
|
+
if finalize is False:
|
|
171
|
+
h = h[:, :-self.pre_lookahead_len * self.token_mel_ratio]
|
|
172
|
+
|
|
173
|
+
h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
|
|
174
|
+
mel_len1, mel_len2 = prompt_feat.shape[1], h.shape[1] - prompt_feat.shape[1]
|
|
175
|
+
h = self.encoder_proj(h)
|
|
176
|
+
|
|
177
|
+
# # get conditions
|
|
178
|
+
conds = torch.zeros([B, mel_len1 + mel_len2, self.output_size], device=token.device).to(h.dtype)
|
|
179
|
+
conds[:, :mel_len1] = prompt_feat
|
|
180
|
+
conds = conds.transpose(1, 2)
|
|
181
|
+
|
|
182
|
+
mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
|
|
183
|
+
|
|
184
|
+
if mask.shape[0] != B:
|
|
185
|
+
mask = mask.repeat(B, 1, 1)
|
|
186
|
+
|
|
187
|
+
feat, _ = self.decoder(
|
|
188
|
+
mu=h.transpose(1, 2).contiguous(),
|
|
189
|
+
mask=mask,
|
|
190
|
+
spks=embedding,
|
|
191
|
+
cond=conds,
|
|
192
|
+
n_timesteps=n_timesteps,
|
|
193
|
+
noised_mels=noised_mels,
|
|
194
|
+
meanflow=meanflow,
|
|
195
|
+
)
|
|
196
|
+
feat = feat[:, :, mel_len1:]
|
|
197
|
+
assert feat.shape[2] == mel_len2
|
|
198
|
+
return feat, None # NOTE jrm: why are they returning None here?
|