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,294 @@
|
|
|
1
|
+
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu)
|
|
2
|
+
# 2024 Alibaba Inc (Xiang Lyu)
|
|
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
|
+
# Modified from ESPnet(https://github.com/espnet/espnet)
|
|
16
|
+
"""Positonal Encoding Module."""
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from typing import Tuple, Union
|
|
20
|
+
|
|
21
|
+
import torch
|
|
22
|
+
import torch.nn.functional as F
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PositionalEncoding(torch.nn.Module):
|
|
27
|
+
"""Positional encoding.
|
|
28
|
+
|
|
29
|
+
:param int d_model: embedding dim
|
|
30
|
+
:param float dropout_rate: dropout rate
|
|
31
|
+
:param int max_len: maximum input length
|
|
32
|
+
|
|
33
|
+
PE(pos, 2i) = sin(pos/(10000^(2i/dmodel)))
|
|
34
|
+
PE(pos, 2i+1) = cos(pos/(10000^(2i/dmodel)))
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self,
|
|
38
|
+
d_model: int,
|
|
39
|
+
dropout_rate: float,
|
|
40
|
+
max_len: int = 5000,
|
|
41
|
+
reverse: bool = False):
|
|
42
|
+
"""Construct an PositionalEncoding object."""
|
|
43
|
+
super().__init__()
|
|
44
|
+
self.d_model = d_model
|
|
45
|
+
self.xscale = math.sqrt(self.d_model)
|
|
46
|
+
self.dropout = torch.nn.Dropout(p=dropout_rate)
|
|
47
|
+
self.max_len = max_len
|
|
48
|
+
|
|
49
|
+
self.pe = torch.zeros(self.max_len, self.d_model)
|
|
50
|
+
position = torch.arange(0, self.max_len,
|
|
51
|
+
dtype=torch.float32).unsqueeze(1)
|
|
52
|
+
div_term = torch.exp(
|
|
53
|
+
torch.arange(0, self.d_model, 2, dtype=torch.float32) *
|
|
54
|
+
-(math.log(10000.0) / self.d_model))
|
|
55
|
+
self.pe[:, 0::2] = torch.sin(position * div_term)
|
|
56
|
+
self.pe[:, 1::2] = torch.cos(position * div_term)
|
|
57
|
+
self.pe = self.pe.unsqueeze(0)
|
|
58
|
+
|
|
59
|
+
def forward(self,
|
|
60
|
+
x: torch.Tensor,
|
|
61
|
+
offset: Union[int, torch.Tensor] = 0) \
|
|
62
|
+
-> Tuple[torch.Tensor, torch.Tensor]:
|
|
63
|
+
"""Add positional encoding.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
x (torch.Tensor): Input. Its shape is (batch, time, ...)
|
|
67
|
+
offset (int, torch.tensor): position offset
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
torch.Tensor: Encoded tensor. Its shape is (batch, time, ...)
|
|
71
|
+
torch.Tensor: for compatibility to RelPositionalEncoding
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
self.pe = self.pe.to(x.device)
|
|
75
|
+
pos_emb = self.position_encoding(offset, x.size(1), False)
|
|
76
|
+
x = x * self.xscale + pos_emb
|
|
77
|
+
return self.dropout(x), self.dropout(pos_emb)
|
|
78
|
+
|
|
79
|
+
def position_encoding(self,
|
|
80
|
+
offset: Union[int, torch.Tensor],
|
|
81
|
+
size: int,
|
|
82
|
+
apply_dropout: bool = True) -> torch.Tensor:
|
|
83
|
+
""" For getting encoding in a streaming fashion
|
|
84
|
+
|
|
85
|
+
Attention!!!!!
|
|
86
|
+
we apply dropout only once at the whole utterance level in a none
|
|
87
|
+
streaming way, but will call this function several times with
|
|
88
|
+
increasing input size in a streaming scenario, so the dropout will
|
|
89
|
+
be applied several times.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
offset (int or torch.tensor): start offset
|
|
93
|
+
size (int): required size of position encoding
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
torch.Tensor: Corresponding encoding
|
|
97
|
+
"""
|
|
98
|
+
# How to subscript a Union type:
|
|
99
|
+
# https://github.com/pytorch/pytorch/issues/69434
|
|
100
|
+
if isinstance(offset, int):
|
|
101
|
+
assert offset + size <= self.max_len
|
|
102
|
+
pos_emb = self.pe[:, offset:offset + size]
|
|
103
|
+
elif isinstance(offset, torch.Tensor) and offset.dim() == 0: # scalar
|
|
104
|
+
assert offset + size <= self.max_len
|
|
105
|
+
pos_emb = self.pe[:, offset:offset + size]
|
|
106
|
+
else: # for batched streaming decoding on GPU
|
|
107
|
+
assert torch.max(offset) + size <= self.max_len
|
|
108
|
+
index = offset.unsqueeze(1) + \
|
|
109
|
+
torch.arange(0, size).to(offset.device) # B X T
|
|
110
|
+
flag = index > 0
|
|
111
|
+
# remove negative offset
|
|
112
|
+
index = index * flag
|
|
113
|
+
pos_emb = F.embedding(index, self.pe[0]) # B X T X d_model
|
|
114
|
+
|
|
115
|
+
if apply_dropout:
|
|
116
|
+
pos_emb = self.dropout(pos_emb)
|
|
117
|
+
return pos_emb
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class RelPositionalEncoding(PositionalEncoding):
|
|
121
|
+
"""Relative positional encoding module.
|
|
122
|
+
See : Appendix B in https://arxiv.org/abs/1901.02860
|
|
123
|
+
Args:
|
|
124
|
+
d_model (int): Embedding dimension.
|
|
125
|
+
dropout_rate (float): Dropout rate.
|
|
126
|
+
max_len (int): Maximum input length.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
|
|
130
|
+
"""Initialize class."""
|
|
131
|
+
super().__init__(d_model, dropout_rate, max_len, reverse=True)
|
|
132
|
+
|
|
133
|
+
def forward(self,
|
|
134
|
+
x: torch.Tensor,
|
|
135
|
+
offset: Union[int, torch.Tensor] = 0) \
|
|
136
|
+
-> Tuple[torch.Tensor, torch.Tensor]:
|
|
137
|
+
"""Compute positional encoding.
|
|
138
|
+
Args:
|
|
139
|
+
x (torch.Tensor): Input tensor (batch, time, `*`).
|
|
140
|
+
Returns:
|
|
141
|
+
torch.Tensor: Encoded tensor (batch, time, `*`).
|
|
142
|
+
torch.Tensor: Positional embedding tensor (1, time, `*`).
|
|
143
|
+
"""
|
|
144
|
+
self.pe = self.pe.to(x.device)
|
|
145
|
+
x = x * self.xscale
|
|
146
|
+
pos_emb = self.position_encoding(offset, x.size(1), False)
|
|
147
|
+
return self.dropout(x), self.dropout(pos_emb)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class WhisperPositionalEncoding(PositionalEncoding):
|
|
151
|
+
""" Sinusoids position encoding used in openai-whisper.encoder
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(self, d_model: int, dropout_rate: float, max_len: int = 1500):
|
|
155
|
+
super().__init__(d_model, dropout_rate, max_len)
|
|
156
|
+
self.xscale = 1.0
|
|
157
|
+
log_timescale_increment = np.log(10000) / (d_model // 2 - 1)
|
|
158
|
+
inv_timescales = torch.exp(-log_timescale_increment *
|
|
159
|
+
torch.arange(d_model // 2))
|
|
160
|
+
scaled_time = torch.arange(max_len)[:, np.newaxis] * \
|
|
161
|
+
inv_timescales[np.newaxis, :]
|
|
162
|
+
pe = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
|
|
163
|
+
delattr(self, "pe")
|
|
164
|
+
self.register_buffer("pe", pe.unsqueeze(0))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class LearnablePositionalEncoding(PositionalEncoding):
|
|
168
|
+
""" Learnable position encoding used in openai-whisper.decoder
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(self, d_model: int, dropout_rate: float, max_len: int = 448):
|
|
172
|
+
super().__init__(d_model, dropout_rate, max_len)
|
|
173
|
+
# NOTE(xcsong): overwrite self.pe & self.xscale
|
|
174
|
+
self.pe = torch.nn.Parameter(torch.empty(1, max_len, d_model))
|
|
175
|
+
self.xscale = 1.0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class NoPositionalEncoding(torch.nn.Module):
|
|
179
|
+
""" No position encoding
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def __init__(self, d_model: int, dropout_rate: float):
|
|
183
|
+
super().__init__()
|
|
184
|
+
self.d_model = d_model
|
|
185
|
+
self.dropout = torch.nn.Dropout(p=dropout_rate)
|
|
186
|
+
|
|
187
|
+
def forward(self,
|
|
188
|
+
x: torch.Tensor,
|
|
189
|
+
offset: Union[int, torch.Tensor] = 0) \
|
|
190
|
+
-> Tuple[torch.Tensor, torch.Tensor]:
|
|
191
|
+
""" Just return zero vector for interface compatibility
|
|
192
|
+
"""
|
|
193
|
+
pos_emb = torch.zeros(1, x.size(1), self.d_model).to(x.device)
|
|
194
|
+
return self.dropout(x), pos_emb
|
|
195
|
+
|
|
196
|
+
def position_encoding(self, offset: Union[int, torch.Tensor],
|
|
197
|
+
size: int) -> torch.Tensor:
|
|
198
|
+
return torch.zeros(1, size, self.d_model)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class EspnetRelPositionalEncoding(torch.nn.Module):
|
|
202
|
+
"""Relative positional encoding module (new implementation).
|
|
203
|
+
|
|
204
|
+
Details can be found in https://github.com/espnet/espnet/pull/2816.
|
|
205
|
+
|
|
206
|
+
See : Appendix B in https://arxiv.org/abs/1901.02860
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
d_model (int): Embedding dimension.
|
|
210
|
+
dropout_rate (float): Dropout rate.
|
|
211
|
+
max_len (int): Maximum input length.
|
|
212
|
+
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
|
|
216
|
+
"""Construct an PositionalEncoding object."""
|
|
217
|
+
super(EspnetRelPositionalEncoding, self).__init__()
|
|
218
|
+
self.d_model = d_model
|
|
219
|
+
self.xscale = math.sqrt(self.d_model)
|
|
220
|
+
self.dropout = torch.nn.Dropout(p=dropout_rate)
|
|
221
|
+
self.pe = None
|
|
222
|
+
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
|
|
223
|
+
|
|
224
|
+
def extend_pe(self, x: torch.Tensor):
|
|
225
|
+
"""Reset the positional encodings."""
|
|
226
|
+
if self.pe is not None:
|
|
227
|
+
# self.pe contains both positive and negative parts
|
|
228
|
+
# the length of self.pe is 2 * input_len - 1
|
|
229
|
+
if self.pe.size(1) >= x.size(1) * 2 - 1:
|
|
230
|
+
if self.pe.dtype != x.dtype or self.pe.device != x.device:
|
|
231
|
+
self.pe = self.pe.to(dtype=x.dtype, device=x.device)
|
|
232
|
+
return
|
|
233
|
+
# Suppose `i` means to the position of query vecotr and `j` means the
|
|
234
|
+
# position of key vector. We use position relative positions when keys
|
|
235
|
+
# are to the left (i>j) and negative relative positions otherwise (i<j).
|
|
236
|
+
pe_positive = torch.zeros(x.size(1), self.d_model)
|
|
237
|
+
pe_negative = torch.zeros(x.size(1), self.d_model)
|
|
238
|
+
position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
|
|
239
|
+
div_term = torch.exp(
|
|
240
|
+
torch.arange(0, self.d_model, 2, dtype=torch.float32)
|
|
241
|
+
* -(math.log(10000.0) / self.d_model)
|
|
242
|
+
)
|
|
243
|
+
pe_positive[:, 0::2] = torch.sin(position * div_term)
|
|
244
|
+
pe_positive[:, 1::2] = torch.cos(position * div_term)
|
|
245
|
+
pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
|
|
246
|
+
pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
|
|
247
|
+
|
|
248
|
+
# Reserve the order of positive indices and concat both positive and
|
|
249
|
+
# negative indices. This is used to support the shifting trick
|
|
250
|
+
# as in https://arxiv.org/abs/1901.02860
|
|
251
|
+
pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
|
|
252
|
+
pe_negative = pe_negative[1:].unsqueeze(0)
|
|
253
|
+
pe = torch.cat([pe_positive, pe_negative], dim=1)
|
|
254
|
+
self.pe = pe.to(device=x.device, dtype=x.dtype)
|
|
255
|
+
|
|
256
|
+
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \
|
|
257
|
+
-> Tuple[torch.Tensor, torch.Tensor]:
|
|
258
|
+
"""Add positional encoding.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
x (torch.Tensor): Input tensor (batch, time, `*`).
|
|
262
|
+
|
|
263
|
+
Returns:
|
|
264
|
+
torch.Tensor: Encoded tensor (batch, time, `*`).
|
|
265
|
+
|
|
266
|
+
"""
|
|
267
|
+
self.extend_pe(x)
|
|
268
|
+
x = x * self.xscale
|
|
269
|
+
pos_emb = self.position_encoding(size=x.size(1), offset=offset)
|
|
270
|
+
return self.dropout(x), self.dropout(pos_emb)
|
|
271
|
+
|
|
272
|
+
def position_encoding(self,
|
|
273
|
+
offset: Union[int, torch.Tensor],
|
|
274
|
+
size: int) -> torch.Tensor:
|
|
275
|
+
""" For getting encoding in a streaming fashion
|
|
276
|
+
|
|
277
|
+
Attention!!!!!
|
|
278
|
+
we apply dropout only once at the whole utterance level in a none
|
|
279
|
+
streaming way, but will call this function several times with
|
|
280
|
+
increasing input size in a streaming scenario, so the dropout will
|
|
281
|
+
be applied several times.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
offset (int or torch.tensor): start offset
|
|
285
|
+
size (int): required size of position encoding
|
|
286
|
+
|
|
287
|
+
Returns:
|
|
288
|
+
torch.Tensor: Corresponding encoding
|
|
289
|
+
"""
|
|
290
|
+
pos_emb = self.pe[
|
|
291
|
+
:,
|
|
292
|
+
self.pe.size(1) // 2 - size + 1: self.pe.size(1) // 2 + size,
|
|
293
|
+
]
|
|
294
|
+
return pos_emb
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu)
|
|
2
|
+
# 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn)
|
|
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
|
+
# Modified from ESPnet(https://github.com/espnet/espnet)
|
|
16
|
+
"""Encoder self-attention layer definition."""
|
|
17
|
+
|
|
18
|
+
from typing import Optional, Tuple
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
from torch import nn
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TransformerEncoderLayer(nn.Module):
|
|
25
|
+
"""Encoder layer module.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
size (int): Input dimension.
|
|
29
|
+
self_attn (torch.nn.Module): Self-attention module instance.
|
|
30
|
+
`MultiHeadedAttention` or `RelPositionMultiHeadedAttention`
|
|
31
|
+
instance can be used as the argument.
|
|
32
|
+
feed_forward (torch.nn.Module): Feed-forward module instance.
|
|
33
|
+
`PositionwiseFeedForward`, instance can be used as the argument.
|
|
34
|
+
dropout_rate (float): Dropout rate.
|
|
35
|
+
normalize_before (bool):
|
|
36
|
+
True: use layer_norm before each sub-block.
|
|
37
|
+
False: to use layer_norm after each sub-block.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
size: int,
|
|
43
|
+
self_attn: torch.nn.Module,
|
|
44
|
+
feed_forward: torch.nn.Module,
|
|
45
|
+
dropout_rate: float,
|
|
46
|
+
normalize_before: bool = True,
|
|
47
|
+
):
|
|
48
|
+
"""Construct an EncoderLayer object."""
|
|
49
|
+
super().__init__()
|
|
50
|
+
self.self_attn = self_attn
|
|
51
|
+
self.feed_forward = feed_forward
|
|
52
|
+
self.norm1 = nn.LayerNorm(size, eps=1e-12)
|
|
53
|
+
self.norm2 = nn.LayerNorm(size, eps=1e-12)
|
|
54
|
+
self.dropout = nn.Dropout(dropout_rate)
|
|
55
|
+
self.size = size
|
|
56
|
+
self.normalize_before = normalize_before
|
|
57
|
+
|
|
58
|
+
def forward(
|
|
59
|
+
self,
|
|
60
|
+
x: torch.Tensor,
|
|
61
|
+
mask: torch.Tensor,
|
|
62
|
+
pos_emb: torch.Tensor,
|
|
63
|
+
mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
|
64
|
+
att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
|
65
|
+
cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
|
66
|
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
67
|
+
"""Compute encoded features.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
x (torch.Tensor): (#batch, time, size)
|
|
71
|
+
mask (torch.Tensor): Mask tensor for the input (#batch, time,time),
|
|
72
|
+
(0, 0, 0) means fake mask.
|
|
73
|
+
pos_emb (torch.Tensor): just for interface compatibility
|
|
74
|
+
to ConformerEncoderLayer
|
|
75
|
+
mask_pad (torch.Tensor): does not used in transformer layer,
|
|
76
|
+
just for unified api with conformer.
|
|
77
|
+
att_cache (torch.Tensor): Cache tensor of the KEY & VALUE
|
|
78
|
+
(#batch=1, head, cache_t1, d_k * 2), head * d_k == size.
|
|
79
|
+
cnn_cache (torch.Tensor): Convolution cache in conformer layer
|
|
80
|
+
(#batch=1, size, cache_t2), not used here, it's for interface
|
|
81
|
+
compatibility to ConformerEncoderLayer.
|
|
82
|
+
Returns:
|
|
83
|
+
torch.Tensor: Output tensor (#batch, time, size).
|
|
84
|
+
torch.Tensor: Mask tensor (#batch, time, time).
|
|
85
|
+
torch.Tensor: att_cache tensor,
|
|
86
|
+
(#batch=1, head, cache_t1 + time, d_k * 2).
|
|
87
|
+
torch.Tensor: cnn_cahce tensor (#batch=1, size, cache_t2).
|
|
88
|
+
|
|
89
|
+
"""
|
|
90
|
+
residual = x
|
|
91
|
+
if self.normalize_before:
|
|
92
|
+
x = self.norm1(x)
|
|
93
|
+
x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb=pos_emb, cache=att_cache)
|
|
94
|
+
x = residual + self.dropout(x_att)
|
|
95
|
+
if not self.normalize_before:
|
|
96
|
+
x = self.norm1(x)
|
|
97
|
+
|
|
98
|
+
residual = x
|
|
99
|
+
if self.normalize_before:
|
|
100
|
+
x = self.norm2(x)
|
|
101
|
+
x = residual + self.dropout(self.feed_forward(x))
|
|
102
|
+
if not self.normalize_before:
|
|
103
|
+
x = self.norm2(x)
|
|
104
|
+
|
|
105
|
+
fake_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
|
|
106
|
+
return x, mask, new_att_cache, fake_cnn_cache
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class ConformerEncoderLayer(nn.Module):
|
|
110
|
+
"""Encoder layer module.
|
|
111
|
+
Args:
|
|
112
|
+
size (int): Input dimension.
|
|
113
|
+
self_attn (torch.nn.Module): Self-attention module instance.
|
|
114
|
+
`MultiHeadedAttention` or `RelPositionMultiHeadedAttention`
|
|
115
|
+
instance can be used as the argument.
|
|
116
|
+
feed_forward (torch.nn.Module): Feed-forward module instance.
|
|
117
|
+
`PositionwiseFeedForward` instance can be used as the argument.
|
|
118
|
+
feed_forward_macaron (torch.nn.Module): Additional feed-forward module
|
|
119
|
+
instance.
|
|
120
|
+
`PositionwiseFeedForward` instance can be used as the argument.
|
|
121
|
+
conv_module (torch.nn.Module): Convolution module instance.
|
|
122
|
+
`ConvlutionModule` instance can be used as the argument.
|
|
123
|
+
dropout_rate (float): Dropout rate.
|
|
124
|
+
normalize_before (bool):
|
|
125
|
+
True: use layer_norm before each sub-block.
|
|
126
|
+
False: use layer_norm after each sub-block.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
size: int,
|
|
132
|
+
self_attn: torch.nn.Module,
|
|
133
|
+
feed_forward: Optional[nn.Module] = None,
|
|
134
|
+
feed_forward_macaron: Optional[nn.Module] = None,
|
|
135
|
+
conv_module: Optional[nn.Module] = None,
|
|
136
|
+
dropout_rate: float = 0.1,
|
|
137
|
+
normalize_before: bool = True,
|
|
138
|
+
):
|
|
139
|
+
"""Construct an EncoderLayer object."""
|
|
140
|
+
super().__init__()
|
|
141
|
+
self.self_attn = self_attn
|
|
142
|
+
self.feed_forward = feed_forward
|
|
143
|
+
self.feed_forward_macaron = feed_forward_macaron
|
|
144
|
+
self.conv_module = conv_module
|
|
145
|
+
self.norm_ff = nn.LayerNorm(size, eps=1e-12) # for the FNN module
|
|
146
|
+
self.norm_mha = nn.LayerNorm(size, eps=1e-12) # for the MHA module
|
|
147
|
+
if feed_forward_macaron is not None:
|
|
148
|
+
self.norm_ff_macaron = nn.LayerNorm(size, eps=1e-12)
|
|
149
|
+
self.ff_scale = 0.5
|
|
150
|
+
else:
|
|
151
|
+
self.ff_scale = 1.0
|
|
152
|
+
if self.conv_module is not None:
|
|
153
|
+
self.norm_conv = nn.LayerNorm(size, eps=1e-12) # for the CNN module
|
|
154
|
+
self.norm_final = nn.LayerNorm(
|
|
155
|
+
size, eps=1e-12) # for the final output of the block
|
|
156
|
+
self.dropout = nn.Dropout(dropout_rate)
|
|
157
|
+
self.size = size
|
|
158
|
+
self.normalize_before = normalize_before
|
|
159
|
+
|
|
160
|
+
def forward(
|
|
161
|
+
self,
|
|
162
|
+
x: torch.Tensor,
|
|
163
|
+
mask: torch.Tensor,
|
|
164
|
+
pos_emb: torch.Tensor,
|
|
165
|
+
mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
|
166
|
+
att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
|
167
|
+
cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
|
168
|
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
169
|
+
"""Compute encoded features.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
x (torch.Tensor): (#batch, time, size)
|
|
173
|
+
mask (torch.Tensor): Mask tensor for the input (#batch, time,time),
|
|
174
|
+
(0, 0, 0) means fake mask.
|
|
175
|
+
pos_emb (torch.Tensor): positional encoding, must not be None
|
|
176
|
+
for ConformerEncoderLayer.
|
|
177
|
+
mask_pad (torch.Tensor): batch padding mask used for conv module.
|
|
178
|
+
(#batch, 1,time), (0, 0, 0) means fake mask.
|
|
179
|
+
att_cache (torch.Tensor): Cache tensor of the KEY & VALUE
|
|
180
|
+
(#batch=1, head, cache_t1, d_k * 2), head * d_k == size.
|
|
181
|
+
cnn_cache (torch.Tensor): Convolution cache in conformer layer
|
|
182
|
+
(#batch=1, size, cache_t2)
|
|
183
|
+
Returns:
|
|
184
|
+
torch.Tensor: Output tensor (#batch, time, size).
|
|
185
|
+
torch.Tensor: Mask tensor (#batch, time, time).
|
|
186
|
+
torch.Tensor: att_cache tensor,
|
|
187
|
+
(#batch=1, head, cache_t1 + time, d_k * 2).
|
|
188
|
+
torch.Tensor: cnn_cahce tensor (#batch, size, cache_t2).
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
# whether to use macaron style
|
|
192
|
+
if self.feed_forward_macaron is not None:
|
|
193
|
+
residual = x
|
|
194
|
+
if self.normalize_before:
|
|
195
|
+
x = self.norm_ff_macaron(x)
|
|
196
|
+
x = residual + self.ff_scale * self.dropout(
|
|
197
|
+
self.feed_forward_macaron(x))
|
|
198
|
+
if not self.normalize_before:
|
|
199
|
+
x = self.norm_ff_macaron(x)
|
|
200
|
+
|
|
201
|
+
# multi-headed self-attention module
|
|
202
|
+
residual = x
|
|
203
|
+
if self.normalize_before:
|
|
204
|
+
x = self.norm_mha(x)
|
|
205
|
+
x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb,
|
|
206
|
+
att_cache)
|
|
207
|
+
x = residual + self.dropout(x_att)
|
|
208
|
+
if not self.normalize_before:
|
|
209
|
+
x = self.norm_mha(x)
|
|
210
|
+
|
|
211
|
+
# convolution module
|
|
212
|
+
# Fake new cnn cache here, and then change it in conv_module
|
|
213
|
+
new_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
|
|
214
|
+
if self.conv_module is not None:
|
|
215
|
+
residual = x
|
|
216
|
+
if self.normalize_before:
|
|
217
|
+
x = self.norm_conv(x)
|
|
218
|
+
x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
|
|
219
|
+
x = residual + self.dropout(x)
|
|
220
|
+
|
|
221
|
+
if not self.normalize_before:
|
|
222
|
+
x = self.norm_conv(x)
|
|
223
|
+
|
|
224
|
+
# feed forward module
|
|
225
|
+
residual = x
|
|
226
|
+
if self.normalize_before:
|
|
227
|
+
x = self.norm_ff(x)
|
|
228
|
+
|
|
229
|
+
x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
|
|
230
|
+
if not self.normalize_before:
|
|
231
|
+
x = self.norm_ff(x)
|
|
232
|
+
|
|
233
|
+
if self.conv_module is not None:
|
|
234
|
+
x = self.norm_final(x)
|
|
235
|
+
|
|
236
|
+
return x, mask, new_att_cache, new_cnn_cache
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Copyright (c) 2019 Shigeki Karita
|
|
2
|
+
# 2020 Mobvoi Inc (Binbin Zhang)
|
|
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
|
+
"""Positionwise feed forward layer definition."""
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PositionwiseFeedForward(torch.nn.Module):
|
|
21
|
+
"""Positionwise feed forward layer.
|
|
22
|
+
|
|
23
|
+
FeedForward are appied on each position of the sequence.
|
|
24
|
+
The output dim is same with the input dim.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
idim (int): Input dimenstion.
|
|
28
|
+
hidden_units (int): The number of hidden units.
|
|
29
|
+
dropout_rate (float): Dropout rate.
|
|
30
|
+
activation (torch.nn.Module): Activation function
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
idim: int,
|
|
36
|
+
hidden_units: int,
|
|
37
|
+
dropout_rate: float,
|
|
38
|
+
activation: torch.nn.Module = torch.nn.ReLU(),
|
|
39
|
+
):
|
|
40
|
+
"""Construct a PositionwiseFeedForward object."""
|
|
41
|
+
super(PositionwiseFeedForward, self).__init__()
|
|
42
|
+
self.w_1 = torch.nn.Linear(idim, hidden_units)
|
|
43
|
+
self.activation = activation
|
|
44
|
+
self.dropout = torch.nn.Dropout(dropout_rate)
|
|
45
|
+
self.w_2 = torch.nn.Linear(hidden_units, idim)
|
|
46
|
+
|
|
47
|
+
def forward(self, xs: torch.Tensor) -> torch.Tensor:
|
|
48
|
+
"""Forward function.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
xs: input tensor (B, L, D)
|
|
52
|
+
Returns:
|
|
53
|
+
output tensor, (B, L, D)
|
|
54
|
+
"""
|
|
55
|
+
return self.w_2(self.dropout(self.activation(self.w_1(xs))))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class MoEFFNLayer(torch.nn.Module):
|
|
59
|
+
"""
|
|
60
|
+
Mixture of expert with Positionwise feed forward layer
|
|
61
|
+
See also figure 1 in https://arxiv.org/pdf/2305.15663.pdf
|
|
62
|
+
The output dim is same with the input dim.
|
|
63
|
+
|
|
64
|
+
Modified from https://github.com/Lightning-AI/lit-gpt/pull/823
|
|
65
|
+
https://github.com/mistralai/mistral-src/blob/b46d6/moe_one_file_ref.py#L203-L219
|
|
66
|
+
Args:
|
|
67
|
+
n_expert: number of expert.
|
|
68
|
+
n_expert_per_token: The actual number of experts used for each frame
|
|
69
|
+
idim (int): Input dimenstion.
|
|
70
|
+
hidden_units (int): The number of hidden units.
|
|
71
|
+
dropout_rate (float): Dropout rate.
|
|
72
|
+
activation (torch.nn.Module): Activation function
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
n_expert: int,
|
|
78
|
+
n_expert_per_token: int,
|
|
79
|
+
idim: int,
|
|
80
|
+
hidden_units: int,
|
|
81
|
+
dropout_rate: float,
|
|
82
|
+
activation: torch.nn.Module = torch.nn.ReLU(),
|
|
83
|
+
):
|
|
84
|
+
super(MoEFFNLayer, self).__init__()
|
|
85
|
+
self.gate = torch.nn.Linear(idim, n_expert, bias=False)
|
|
86
|
+
self.experts = torch.nn.ModuleList(
|
|
87
|
+
PositionwiseFeedForward(idim, hidden_units, dropout_rate,
|
|
88
|
+
activation) for _ in range(n_expert))
|
|
89
|
+
self.n_expert_per_token = n_expert_per_token
|
|
90
|
+
|
|
91
|
+
def forward(self, xs: torch.Tensor) -> torch.Tensor:
|
|
92
|
+
"""Foward function.
|
|
93
|
+
Args:
|
|
94
|
+
xs: input tensor (B, L, D)
|
|
95
|
+
Returns:
|
|
96
|
+
output tensor, (B, L, D)
|
|
97
|
+
|
|
98
|
+
"""
|
|
99
|
+
B, L, D = xs.size(
|
|
100
|
+
) # batch size, sequence length, embedding dimension (idim)
|
|
101
|
+
xs = xs.view(-1, D) # (B*L, D)
|
|
102
|
+
router = self.gate(xs) # (B*L, n_expert)
|
|
103
|
+
logits, indices = torch.topk(
|
|
104
|
+
router, self.n_expert_per_token
|
|
105
|
+
) # probs:(B*L, n_expert), indices: (B*L, n_expert)
|
|
106
|
+
weights = torch.nn.functional.softmax(
|
|
107
|
+
logits, dim=1,
|
|
108
|
+
dtype=torch.float).to(dtype=xs.dtype) # (B*L, n_expert_per_token)
|
|
109
|
+
output = torch.zeros_like(xs) # (B*L, D)
|
|
110
|
+
for i, expert in enumerate(self.experts):
|
|
111
|
+
mask = indices == i
|
|
112
|
+
batch_idx, ith_expert = torch.where(mask)
|
|
113
|
+
output[batch_idx] += weights[batch_idx, ith_expert, None] * expert(
|
|
114
|
+
xs[batch_idx])
|
|
115
|
+
return output.view(B, L, D)
|