-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspear_tts.py
2042 lines (1621 loc) · 76.5 KB
/
spear_tts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
from pathlib import Path
from functools import partial
from random import random
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch import Tensor, nn, einsum, IntTensor, LongTensor
from torch.nn import Module, ModuleList
from torch.utils.data import Dataset
from einops import rearrange, repeat, pack, reduce
from einops.layers.torch import Rearrange
from beartype import beartype
from beartype.door import is_bearable
from beartype.typing import Optional, Union, Callable, Literal, Tuple, List
from audiolm_pytorch import FairseqVQWav2Vec, HubertWithKmeans
from audiolm_pytorch.data import get_dataloader
from rotary_embedding_torch import RotaryEmbedding
from x_clip.tokenizer import tokenizer
from attend import Attend
from distributed import all_gather
# 定义 FloatTensor 类型别名,可以是 CPU 上的 FloatTensor 或 CUDA 上的 FloatTensor
FloatTensor = Union[
torch.FloatTensor, # CPU 上的 32 位浮点张量
torch.cuda.FloatTensor # CUDA 上的 32 位浮点张量
]
def exists(val):
"""
检查一个值是否存在(即不为 None)。
Args:
val: 需要检查的值。
Returns:
bool: 如果值不为 None,则返回 True;否则返回 False。
"""
return val is not None
def default(val, d):
"""
如果值存在(即不为 None),则返回该值;否则返回默认值。
Args:
val: 需要检查的值。
d: 默认值。
Returns:
如果 val 存在,则返回 val;否则返回 d。
"""
return val if exists(val) else d
def empty(t: Tensor):
"""
检查一个张量是否为空(即元素数量为零)。
Args:
t (torch.Tensor): 需要检查的张量。
Returns:
bool: 如果张量为空,则返回 True;否则返回 False。
"""
return t.numel() == 0
def l2norm(t):
"""
对张量进行 L2 归一化。
L2 归一化会将张量的每个向量(通常是最后一个维度)归一化为单位向量。
Args:
t (torch.Tensor): 需要归一化的张量。
Returns:
torch.Tensor: 归一化后的张量。
"""
return F.normalize(t, dim = -1)
def set_eos_id(t: Tensor, eos_id: int, pad_id: int):
"""
在张量的每个序列末尾添加 EOS(End of Sequence)标识符。
Args:
t (torch.Tensor): 输入张量,形状为 (batch_size, seq_length)。
eos_id (int): EOS 的标识符 ID。
pad_id (int): 填充符的标识符 ID。
Returns:
torch.Tensor: 在每个序列末尾添加了 EOS 标识符后的张量。
"""
# 计算每个序列中第一个 pad_id 之前的位置,作为 EOS 的插入位置
eos_indices = ((t == pad_id).cumsum(dim = -1) == 0).sum(dim = -1, keepdim = True).long()
# 生成一个范围张量,用于索引 batch
batch_range = torch.arange(t.shape[0], device = t.device, dtype = torch.long)
# 重塑为 (batch_size, 1)
batch_range = rearrange(batch_range, '... -> ... 1')
# 在每个序列末尾添加一个填充符
t = F.pad(t, (0, 1), value = pad_id)
# 在指定的位置插入 EOS 标识符
t[batch_range, eos_indices] = eos_id
return t
def batch_unique_consecutive(t, pad_value = 0.):
"""
对批次中的每个序列执行 unique_consecutive 操作,并填充以保持批次形状。
Args:
t (torch.Tensor): 输入张量,形状为 (batch_size, seq_length)。
pad_value (float, optional): 填充值,默认为 0。
Returns:
torch.Tensor: 每个序列经过 unique_consecutive 处理后的张量,形状为 (batch_size, new_seq_length)。
"""
# 对批次中的每个序列执行 unique_consecutive 操作
unique_arr = [torch.unique_consecutive(el) for el in t.unbind(dim = 0)]
# 对处理后的序列进行填充,以保持批次形状
return pad_sequence(unique_arr, batch_first = True, padding_value = pad_value)
def mask_after_eos(target, eos_id, pad_id):
"""
在 EOS 标识符之后的位置应用掩码,将其替换为填充符。
Args:
target (torch.Tensor): 目标张量,形状为 (batch_size, seq_length)。
eos_id (int): EOS 的标识符 ID。
pad_id (int): 填充符的标识符 ID。
Returns:
torch.Tensor: 在 EOS 之后的位置被掩码替换为填充符后的张量。
"""
# 生成一个掩码,标记每个序列中 EOS 之后的位置
mask = (target == eos_id).cumsum(dim = -1) > 0
# 在掩码的末尾添加一个 False 值,以避免最后一个位置被掩码
mask = F.pad(mask, (1, -1), value = False)
# 使用掩码将 EOS 之后的位置替换为填充符
return target.masked_fill(mask, pad_id)
def safe_div(num, den, eps = 1e-10):
"""
安全地执行除法操作,避免除以零。
Args:
num (torch.Tensor): 分子张量。
den (torch.Tensor): 分母张量。
eps (float, optional): 一个极小值,默认为 1e-10。
Returns:
torch.Tensor: 除法结果。
"""
return num / max(den, eps)
def find_first_true_index(bool_tensor, dim = -1):
"""
查找布尔张量中每个序列第一个 True 值的位置。
Args:
bool_tensor (torch.Tensor): 布尔张量。
dim (int, optional): 查找的维度,默认为最后一个维度。
Returns:
torch.Tensor: 每个序列中第一个 True 值的位置索引。
"""
return (bool_tensor.cumsum(dim = dim) == 0).sum(dim = dim)
# freezing and unfreezing helpers
def set_requires_grad_(module: Module, requires_grad: bool):
"""
设置模块中所有参数的 requires_grad 属性。
Args:
module (torch.nn.Module): 需要设置参数的模块。
requires_grad (bool): 是否需要梯度。True 表示需要梯度,False 表示不需要梯度。
"""
for p in module.parameters():
p.requires_grad = requires_grad
def freeze(module: Module):
"""
冻结模块,使其参数不参与梯度计算。
Args:
module (torch.nn.Module): 需要冻结的模块。
"""
set_requires_grad_(module, False)
def unfreeze(module: Module):
"""
解冻模块,使其参数参与梯度计算。
Args:
module (torch.nn.Module): 需要解冻的模块。
"""
set_requires_grad_(module, True)
# sampling helpers
def eval_decorator(fn):
"""
装饰器,用于在函数执行前后切换模型的训练模式。
该装饰器在执行被装饰的函数之前将模型设置为评估模式(eval),执行完毕后恢复之前的训练模式(train)。
Args:
fn (callable): 被装饰的函数。
Returns:
callable: 装饰后的函数。
"""
def inner(self, *args, **kwargs):
was_training = self.training
self.eval()
out = fn(self, *args, **kwargs)
self.train(was_training)
return out
return inner
def log(t, eps = 1e-20):
"""
对张量进行对数运算,并添加一个极小值以避免对数运算中的数值不稳定。
Args:
t (torch.Tensor): 输入张量。
eps (float, optional): 极小值,默认为 1e-20。
Returns:
torch.Tensor: 对数运算后的张量。
"""
return torch.log(t.clamp(min = eps))
def gumbel_noise(t):
"""
生成与输入张量形状相同的 Gumbel 噪声。
Gumbel 噪声常用于实现 Gumbel-Softmax 技巧,用于从离散分布中进行采样。
Args:
t (torch.Tensor): 输入张量。
Returns:
torch.Tensor: 与输入张量形状相同的 Gumbel 噪声。
"""
noise = torch.zeros_like(t).uniform_(0, 1)
return -log(-log(noise))
def gumbel_sample(t, temperature = 1., dim = -1):
"""
使用 Gumbel-Softmax 技巧对输入张量进行采样。
Args:
t (torch.Tensor): 输入张量,通常是 logits。
temperature (float, optional): 温度参数,用于控制采样的平滑程度。默认为 1.0。
dim (int, optional): 采样的维度。默认为最后一个维度。
Returns:
torch.Tensor: 采样后的张量,形状与输入张量相同。
"""
return ((t / max(temperature, 1e-10)) + gumbel_noise(t)).argmax(dim = dim)
def top_p(logits, thres = 0.9):
"""
对 logits 应用 top-p(核采样)方法,保留累计概率不超过阈值的 top tokens。
Args:
logits (torch.Tensor): 输入的 logits 张量。
thres (float, optional): 概率阈值,默认为 0.9。
Returns:
torch.Tensor: 应用 top-p 后的 logits 张量。
"""
# 对 logits 进行降序排序
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
# 计算累计概率
cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# 找到需要移除的 tokens
sorted_indices_to_remove = F.pad(cum_probs > thres, (1, -1), value = 0)
# 将需要移除的 tokens 的 logits 设为负无穷
sorted_logits[sorted_indices_to_remove] = float('-inf')
# 将排序后的 logits 重新排列回原始顺序
sorted_logits = sorted_logits.scatter(-1, sorted_indices, sorted_logits)
# 返回应用 top-p 后的 logits 张量。
return sorted_logits
def top_k(logits, thres = 0.1, k = None):
"""
对 logits 应用 top-k 方法,保留前 k 个 logits。
Args:
logits (torch.Tensor): 输入的 logits 张量。
thres (float, optional): 比例阈值,用于动态计算 k 值。默认为 0.1。
k (int, optional): 要保留的 top tokens 数量。如果未提供,则根据 thres 计算。
Returns:
torch.Tensor: 应用 top-k 后的 logits 张量。
"""
if not exists(k):
# 根据比例阈值计算 k 值
k = math.ceil(thres * logits.shape[-1])
# 找到前 k 个 logits 和对应的索引
val, ind = torch.topk(logits, k, dim = -1)
# 创建一个全为负无穷的张量
probs = torch.full_like(logits, float('-inf'))
# 将前 k 个 logits 的值填入 probs 中
probs.scatter_(-1, ind, val)
# 返回应用 top-k 后的 logits 张量。
return probs
# residual wrapper
class Residual(nn.Module):
"""
Residual 模块,用于实现残差连接。
Args:
fn (callable): 要应用的函数或模块。
"""
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, **kwargs):
# 前向传播函数,将输入 x 通过函数 fn 处理后与原始输入 x 相加,实现残差连接。
return self.fn(x, **kwargs) + x
# rmsnorm
class RMSNorm(nn.Module):
"""
RMSNorm 模块,实现均方根归一化。
Args:
dim (int): 输入张量的维度。
"""
def __init__(self, dim):
super().__init__()
self.scale = dim ** 0.5
self.gamma = nn.Parameter(torch.ones(dim))
def forward(self, x):
# 前向传播函数,对输入张量进行归一化后乘以缩放因子和 gamma 参数。
return F.normalize(x, dim = -1) * self.scale * self.gamma
# feedforward
class GEGLU(nn.Module):
"""
GEGLU (Gated Linear Unit with Gaussian Error Linear Units) 模块。
GEGLU 是门控线性单元的一种变体,结合了 GLU 和 GELU 激活函数。
它将输入张量沿最后一个维度分成两部分:一部分用于门控,另一部分用于计算输出。
Args:
None
Forward Args:
x (torch.Tensor): 输入张量,形状为 (..., dim)。
"""
def forward(self, x):
"""
前向传播函数,实现 GEGLU 操作。
Args:
x (torch.Tensor): 输入张量,形状为 (..., dim)。
Returns:
torch.Tensor: GEGLU 激活后的输出张量。
"""
# 将输入张量沿最后一个维度分成两部分
x, gate = x.chunk(2, dim = -1)
# 对门控部分应用 GELU 激活函数,并将其与输入张量的第一部分相乘
return F.gelu(gate) * x
def FeedForward(dim, mult = 4, dropout = 0.):
"""
创建一个前馈神经网络模块。
该模块通常用于 Transformer 模型中,作为其前馈子层。
它由 RMSNorm、线性层、GEGLU 激活函数、Dropout 和另一个线性层组成。
Args:
dim (int): 输入和输出的维度。
mult (int, optional): 隐藏层维度的乘数因子,默认为 4。
dropout (float, optional): Dropout 概率,默认为 0。
Returns:
nn.Sequential: 包含前馈网络各层的有序容器。
"""
# 计算隐藏层的维度
dim_inner = int(dim * mult * 2 / 3)
# 返回一个 Sequential 模块,包含以下层:
return nn.Sequential(
RMSNorm(dim), # RMS 归一化层
nn.Linear(dim, dim_inner * 2), # 第一个线性层,将维度从 dim 扩展到 dim_inner * 2
GEGLU(), # GEGLU 激活函数
nn.Dropout(dropout), # Dropout 层
nn.Linear(dim_inner, dim) # 第二个线性层,将维度从 dim_inner 恢复到 dim
)
# attention
class Attention(nn.Module):
"""
多头自注意力机制模块,支持多种配置选项,如因果掩码、旋转位置编码、Flash Attention 等。
参数说明:
- dim: 输入特征的维度。
- dim_head: 每个注意力头的维度,默认为64。
- heads: 注意力头的数量,默认为8。
- kv_heads: 键值对注意力头的数量,如果未指定,则默认与 heads 相同。
- causal: 是否使用因果掩码,默认为 False。
- dim_context: 上下文特征的维度,如果未指定,则默认与 dim 相同。
- dropout: Dropout 概率,默认为0。
- rotary_emb: 旋转位置编码实例,默认为 None。
- flash: 是否使用 Flash Attention,默认为 False。
- add_null_kv: 是否添加空键值对,默认为 False。
"""
def __init__(
self,
dim,
*,
dim_head = 64,
heads = 8,
kv_heads = None,
causal = False,
dim_context = None,
dropout = 0.,
rotary_emb: Optional[RotaryEmbedding] = None,
flash = False,
add_null_kv = False
):
super().__init__()
# 如果未指定上下文维度,则默认为输入维度
dim_context = default(dim_context, dim)
# 初始化多头参数
self.heads = heads
self.kv_heads = default(kv_heads, heads)
assert (self.heads % self.kv_heads) == 0, 'number of key value heads must be divisible by query heads'
# 计算缩放因子
self.scale = dim_head ** -0.5
# 查询向量的总维度
dim_query_inner = heads * dim_head
# 键值对向量的总维度
dim_kv_inner = self.kv_heads * dim_head
# 初始化旋转位置编码
self.rotary_emb = rotary_emb
# 初始化 Attend 模块,用于执行注意力机制
self.attend = Attend(
causal = causal,
flash = flash,
dropout = dropout
)
# 初始化归一化层
self.norm = RMSNorm(dim)
# 初始化 Dropout 层
self.attn_dropout = nn.Dropout(dropout)
# 定义查询向量的线性变换和重排
self.to_q = nn.Sequential(
nn.Linear(dim, dim_query_inner, bias = False),
Rearrange('b n (h d) -> b h n d', h = self.heads)
)
# 定义键值对向量的线性变换和重排
self.to_kv = nn.Sequential(
nn.Linear(dim_context, dim_kv_inner * 2, bias = False),
Rearrange('b n (kv h d) -> kv b h n d', kv = 2, h = self.kv_heads)
)
# 定义输出线性层,将注意力输出映射回原始维度
self.to_out = nn.Linear(dim_query_inner, dim, bias = False)
# 是否添加空键值对
self.add_null_kv = add_null_kv
if add_null_kv:
# 初始化空键值对
self.null_kv = nn.Parameter(torch.randn(2, self.kv_heads, 1, dim_head))
def forward(
self,
x,
context = None,
mask = None,
cache = None,
return_cached_key_values = False
):
"""
前向传播方法,执行多头自注意力机制。
参数说明:
- x: 输入张量,形状为 (批次大小, 序列长度, 特征维度)。
- context: 上下文张量,如果未指定,则默认为输入张量 x。
- mask: 注意力掩码,默认为 None。
- cache: 缓存的键值对张量,默认为 None。
- return_cached_key_values: 是否返回缓存的键值对,默认为 False。
返回:
- 如果 return_cached_key_values 为 False,则返回输出张量。
- 否则,返回输出张量和新的缓存键值对。
"""
# 检查是否提供了上下文
has_context = exists(context)
b = x.shape[0]
# 对输入进行归一化
x = self.norm(x)
# 如果未提供上下文,则上下文默认为输入 x
context = default(context, x)
# 计算查询、键和值向量
q, k, v = (self.to_q(x), *self.to_kv(context))
# 如果提供了缓存,则将缓存的键值对与当前的键值对拼接
if exists(cache):
ck, cv = cache.unbind(dim = 1)
k = torch.cat((ck, k), dim = -2)
v = torch.cat((cv, v), dim = -2)
# 缓存新的键值对
new_cache = torch.stack((k, v), dim = 1)
# 如果使用了旋转位置编码,则旋转查询和键
if exists(self.rotary_emb):
assert not has_context
q, k = self.rotary_emb.rotate_queries_with_cached_keys(q, k)
# 如果添加了空键值对,则将空键值对与当前的键值对拼接
if self.add_null_kv:
assert not exists(self.rotary_emb)
nk, nv = map(lambda t: repeat(t, 'h 1 d -> b h 1 d', b = b), self.null_kv)
k = torch.cat((nk, k), dim = -2)
v = torch.cat((nv, v), dim = -2)
# 如果提供了掩码,则在掩码前填充一个额外的维度
if exists(mask):
mask = F.pad(mask, (1, 0), value = True)
# 执行注意力机制
out = self.attend(q, k, v, mask = mask)
# 重排输出形状
out = rearrange(out, 'b h n d -> b n (h d)')
# 通过线性层映射回原始维度
out = self.to_out(out)
# 如果不需要返回缓存的键值对,则直接返回输出
if not return_cached_key_values:
return out
# 否则,返回输出和新的缓存
return out, new_cache
# transformer
class Transformer(nn.Module):
"""
Transformer 模型类,实现了多头自注意力机制和前馈神经网络的多层堆叠。
参数说明:
- dim: 输入特征的维度。
- depth: Transformer 层的数量。
- dim_head: 每个注意力头的维度,默认为64。
- heads: 注意力头的数量,默认为8。
- kv_heads: 键值对注意力头的数量,如果未指定,则默认与 heads 相同。
- causal: 是否使用因果掩码,默认为 False。
- attn_dropout: 注意力层的 Dropout 概率,默认为0。
- ff_mult: 前馈网络中间层的维度乘数,默认为4。
- ff_dropout: 前馈层的 Dropout 概率,默认为0。
- cross_attend: 是否使用交叉注意力,默认为 False。
- attn_flash: 是否使用 Flash Attention,默认为 False。
"""
def __init__(
self,
*,
dim,
depth,
dim_head = 64,
heads = 8,
kv_heads = None,
causal = False,
attn_dropout = 0.,
ff_mult = 4,
ff_dropout = 0.,
cross_attend = False,
attn_flash = False
):
super().__init__()
# 初始化旋转位置编码
rotary_emb = RotaryEmbedding(dim_head)
# 初始化 Transformer 层列表
self.layers = nn.ModuleList([])
# 逐层构建 Transformer
for _ in range(depth):
# 构建自注意力层
self.layers.append(nn.ModuleList([
Attention(dim = dim, causal = causal, dim_head = dim_head, heads = heads, kv_heads = kv_heads, dropout = attn_dropout, rotary_emb = rotary_emb, flash = attn_flash),
Attention(dim = dim, dim_head = dim_head, heads = heads, dropout = attn_dropout, flash = attn_flash, add_null_kv = True) if cross_attend else None,
# 构建前馈网络层
FeedForward(dim = dim, mult = ff_mult, dropout = ff_dropout)
]))
# 初始化最终的归一化层
self.final_norm = RMSNorm(dim)
def forward(
self,
x,
mask = None,
context = None,
context_mask = None,
cache = None,
return_cache = False,
return_hiddens = False,
early_exit_at_layer = None,
seq_start_pos = None
):
"""
Transformer 的前向传播方法,执行多层自注意力和前馈网络的前向计算。
参数说明:
- x: 输入张量,形状为 (批次大小, 序列长度, 特征维度)。
- mask: 自注意力掩码,默认为 None。
- context: 上下文张量,用于交叉注意力,默认为 None。
- context_mask: 交叉注意力掩码,默认为 None。
- cache: 缓存的键值对张量,默认为 None。
- return_cache: 是否返回缓存的键值对,默认为 False。
- return_hiddens: 是否返回中间隐藏状态,默认为 False。
- early_exit_at_layer: 提前退出的层数,默认为 None。
- seq_start_pos: 序列起始位置,默认为 None。
返回:
- 如果 return_hiddens 和 return_cache 均为 False,则返回输出张量。
- 如果 return_hiddens 为 True,则返回输出张量和中间隐藏状态。
- 如果 return_cache 为 True,则返回输出张量和缓存的键值对。
- 如果同时 return_hiddens 和 return_cache 为 True,则返回输出张量、中间隐藏状态和缓存的键值对。
"""
# 检查是否提供了上下文
has_context = exists(context)
# 如果提供了 seq_start_pos,则生成掩码
if exists(seq_start_pos):
assert not exists(mask)
seq_len = x.shape[-2]
seq_arange = torch.arange(seq_len, device = x.device, dtype = torch.long)
mask = seq_arange >= seq_start_pos[..., None]
# 如果提供了缓存,则处理缓存
if exists(cache):
cached_length, seq_len = cache.shape[-2], x.shape[-2]
assert seq_len > cached_length
x = x[:, cached_length:]
# 初始化缓存和隐藏状态列表
new_cache = []
hiddens = []
# 如果提供了缓存,则使用缓存的键值对;否则使用空迭代器
if exists(cache):
iter_cache = iter(cache.unbind(dim = 1))
else:
iter_cache = iter([])
# 逐层处理 Transformer
for ind, (self_attn, maybe_cross_attn, ff) in enumerate(self.layers):
layer = ind + 1
# 保存输入作为残差连接
residual = x
# 执行自注意力机制
attn_out, key_values = self_attn(x, mask = mask, cache = next(iter_cache, None), return_cached_key_values = True)
x = attn_out + residual
# 将键值对添加到缓存中
new_cache.append(key_values)
# 如果需要交叉注意力,则执行交叉注意力
if exists(maybe_cross_attn):
assert has_context
x = maybe_cross_attn(x, context = context, mask = context_mask) + x
# 执行前馈网络
x = ff(x) + x
# 将中间隐藏状态添加到列表中
hiddens.append(x)
# 如果设置了提前退出,则在指定层退出
if exists(early_exit_at_layer) and early_exit_at_layer == layer:
break
# 如果设置了提前退出,则根据需要返回结果
if exists(early_exit_at_layer):
if return_cache:
return x, torch.stack(new_cache, dim = 1)
return x
# 应用最终的归一化层
out = self.final_norm(x)
# 如果需要返回隐藏状态,则返回输出和隐藏状态
if return_hiddens:
assert not return_cache
return out, torch.stack(hiddens)
# 如果不需要返回缓存,则返回输出
if not return_cache:
return out
# 如果需要返回缓存,则返回输出和缓存
return out, torch.stack(new_cache, dim = 1)
# class
# 定义一个联合类型,表示语音或文本类型
SpeechOrTextLiteral = Union[
Literal['speech'], # 表示语音类型
Literal['text'] # 表示文本类型
]
# 定义一个联合类型,表示语义模型类型
SemanticModelType = Union[
FairseqVQWav2Vec, # 假设这是基于 Fairseq 的 VQWav2Vec 模型
HubertWithKmeans # 假设这是基于 Hubert 和 K-means 的模型
]
class TextToSemantic(Module):
"""
TextToSemantic 类用于将文本输入转换为语义表示。该类集成了文本编码器(如 OpenAI 的 tokenizer 或自定义 tokenizer)、语义模型(如 wav2vec 模型)以及 Transformer 架构,
以实现从文本到语义的映射,并支持条件指导(classifier-free guidance)和对齐正则化(alignment regularization)。
参数说明:
- dim: 输入特征的维度。
- source_depth: 源 Transformer 的层数。
- target_depth: 目标 Transformer 的层数。
- num_text_token_ids: 文本 token 的数量。如果未指定,则需要使用 OpenAI 的 tokenizer 或自定义 tokenizer。
- tokenizer_encode: 自定义 tokenizer 编码函数。如果未指定,则使用 OpenAI 的 tokenizer。
- use_openai_tokenizer: 是否使用 OpenAI 的 tokenizer。如果为 True,则忽略 tokenizer_encode 和 num_text_token_ids 参数。
- wav2vec: 语义模型实例(如基于 audiolm-pytorch 的 wav2vec 模型)。如果未指定,则需要指定 num_semantic_token_ids。
- num_semantic_token_ids: 语义 token 的数量。如果未指定,则需要传入 wav2vec 模型。
- dim_head: 每个注意力头的维度,默认为64。
- heads: 注意力头的数量,默认为8。
- target_kv_heads: 目标 Transformer 中键值对注意力头的数量,用于分组查询注意力以节省解码器推理时的内存。
- attn_dropout: 注意力层的 Dropout 概率,默认为0。
- ff_mult: 前馈网络中间层的维度乘数,默认为4。
- ff_dropout: 前馈层的 Dropout 概率,默认为0。
- semantic_pad_id: 语义 token 的填充 ID,默认为-1。
- text_pad_id: 文本 token 的填充 ID,默认为0。
- autoset_semantic_eos_id: 是否自动设置语义 token 的结束 ID,默认为 True。
- autoset_text_eos_id: 是否自动设置文本 token 的结束 ID,默认为 True。
- attn_flash: 是否使用 Flash Attention,默认为 False。
- cond_drop_prob: 条件指导中条件被丢弃的概率,默认为0。
- target_early_exit_layer: 目标 Transformer 中提前退出的层数,默认为 None。
- detach_early_exit_embed: 是否在提前退出时分离嵌入,默认为 False。
- align_reg_loss_weight: 对齐正则化损失的权重,默认为0.1。
- align_reg_use_logsumexp_pool: 是否使用 logsumexp 池化进行对齐正则化,默认为 True。
- align_reg_logsumexp_pool_temp: logsumexp 池化的温度参数,默认为0.1。
"""
@beartype
def __init__(
self,
dim,
*,
source_depth,
target_depth,
num_text_token_ids = None,
tokenizer_encode: Optional[Callable] = None,
use_openai_tokenizer = False,
wav2vec: Optional[SemanticModelType] = None,
num_semantic_token_ids = None,
dim_head = 64,
heads = 8,
target_kv_heads = None, # for grouped query attention, saving memory on decoder inference
attn_dropout = 0.,
ff_mult = 4,
ff_dropout = 0.,
semantic_pad_id = -1,
text_pad_id = 0,
autoset_semantic_eos_id = True,
autoset_text_eos_id = True,
attn_flash = False,
cond_drop_prob = 0.,
target_early_exit_layer = None,
detach_early_exit_embed = False,
align_reg_loss_weight = 0.1,
align_reg_use_logsumexp_pool = True,
align_reg_logsumexp_pool_temp = 0.1
):
super().__init__()
self.dim = dim
self.wav2vec = wav2vec
# 如果提供了 wav2vec 模型,则冻结其参数
if exists(self.wav2vec):
freeze(self.wav2vec)
self.tokenizer_encode = tokenizer_encode
# 如果使用 OpenAI 的 tokenizer,则忽略 tokenizer_encode 和 num_text_token_ids 参数
if use_openai_tokenizer:
assert not exists(tokenizer_encode)
assert not exists(num_text_token_ids)
self.tokenizer_encode = tokenizer.tokenize
num_text_token_ids = tokenizer.vocab_size
else:
assert exists(num_text_token_ids), 'num_text_token_ids not specified'
# 如果提供了 wav2vec 模型,则语义 token 的数量为 codebook_size;否则需要指定 num_semantic_token_ids
num_semantic_token_ids = wav2vec.codebook_size if exists(wav2vec) else num_semantic_token_ids
assert exists(num_semantic_token_ids), 'you need to either pass in a wav2vec model from audiolm-pytorch, or specify the number of semantic token ids with num_semantic_token_ids'
self.num_semantic_token_ids = num_semantic_token_ids
self.num_text_token_ids = num_text_token_ids
# padding id, for deriving attention mask automatically if not passed in
# 填充 ID,用于在未提供掩码时自动生成注意力掩码
self.semantic_pad_id = semantic_pad_id
self.text_pad_id = text_pad_id
self.pad_id = dict(
speech = semantic_pad_id,
text = text_pad_id
)
# eos id
# 结束 ID
self.autoset_eos_id = dict(
speech = autoset_semantic_eos_id,
text = autoset_text_eos_id
)
self.eos_id = dict(
speech = num_semantic_token_ids,
text = num_text_token_ids
)
# embedding
# 嵌入层
num_semantic_token_ids_with_eos = num_semantic_token_ids + int(autoset_semantic_eos_id)
num_text_token_ids_with_eos = num_text_token_ids + int(autoset_text_eos_id)
semantic_token_emb = nn.Embedding(num_semantic_token_ids_with_eos, dim)
text_token_emb = nn.Embedding(num_text_token_ids_with_eos, dim)
self.semantic_token_emb = semantic_token_emb
self.token_emb = nn.ModuleDict(dict(
speech = semantic_token_emb,
text = text_token_emb
))
# respective start tokens
# 起始 token
self.start_token = nn.ParameterDict(dict(
speech = nn.Parameter(torch.randn(dim)),
text = nn.Parameter(torch.randn(dim))
))
# projection to logits
# 投影到 logit
to_semantic_logit = nn.Linear(dim, num_semantic_token_ids, bias = False)
to_text_logit = nn.Linear(dim, num_text_token_ids, bias = False)
to_semantic_logit.weight = semantic_token_emb.weight
to_text_logit.weight = text_token_emb.weight
self.to_logits = nn.ModuleDict(dict(
speech = to_semantic_logit,
text = to_text_logit
))
# source and target attention layers
# source Transformer
self.source_transformer = Transformer(
dim = dim,
dim_head = dim_head,
heads = heads,
depth = source_depth,
attn_dropout = attn_dropout,
ff_mult = ff_mult,
ff_dropout = ff_dropout,
causal = False,
attn_flash = attn_flash
)
# target Transformer
self.target_transformer = Transformer(
dim = dim,
dim_head = dim_head,
heads = heads,
kv_heads = target_kv_heads,
depth = target_depth,
attn_dropout = attn_dropout,
ff_mult = ff_mult,
ff_dropout = ff_dropout,
causal = True,
cross_attend = True,
attn_flash = attn_flash
)
# classifier free guidance - prob of dropping condition
# CFG
assert 0 <= cond_drop_prob < 1
self.cond_drop_prob = cond_drop_prob
self.align_reg_loss_weight = align_reg_loss_weight # lambda for weight of regularization loss in https://arxiv.org/abs/2309.08773
self.align_reg_use_logsumexp_pool = align_reg_use_logsumexp_pool
self.align_reg_logsumexp_pool_temp = align_reg_logsumexp_pool_temp
# for speculative decoding, to speed up text-to-speech decoding and make real-time TTS approach more feasible with spear-tts
# using early exist strategy so one can train just the same model
self.target_has_early_exit = exists(target_early_exit_layer)
self.early_exit_layer = target_early_exit_layer
if self.target_has_early_exit:
assert 0 < target_early_exit_layer <= target_depth, f'the early exit layer for the speech transformer must be between 1 and {target_depth}'
self.detach_early_exit_embed = detach_early_exit_embed
self.to_early_exit_semantic_logits = nn.Sequential(
Residual(FeedForward(dim)),
RMSNorm(dim),
nn.Linear(dim, num_semantic_token_ids_with_eos, bias = False)
)
@property
def device(self):
"""
获取模型当前所在的设备(CPU 或 GPU)。
返回:
torch.device: 模型所在的设备。
"""
return next(self.parameters()).device
def load(self, path, strict = True):
# Return pkg so that if this function gets called from within a Trainer function call,
# the trainer can also access the package loaded from the checkpoint.
"""
从指定的路径加载模型参数。
参数:
path (str): 模型参数文件的路径。
strict (bool): 是否严格加载模型状态字典,默认为 True。
返回:
dict: 加载的模型状态字典包。
备注:
返回包以便在 Trainer 函数调用中访问加载的检查点。
"""
path = Path(path)
assert path.exists()
# 使用 CPU 映射位置加载模型参数
pkg = torch.load(str(path), map_location = 'cpu')
# 严格加载模型状态字典
self.load_state_dict(pkg['model'], strict = strict)
return pkg