zomehwh commited on
Commit
02259d3
1 Parent(s): 85f12e1
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +16 -0
  2. AR/__init__.py +0 -0
  3. AR/data/__init__.py +0 -0
  4. AR/data/bucket_sampler.py +157 -0
  5. AR/data/data_module.py +66 -0
  6. AR/data/dataset.py +302 -0
  7. AR/models/__init__.py +0 -0
  8. AR/models/t2s_lightning_module.py +128 -0
  9. AR/models/t2s_model.py +298 -0
  10. AR/models/utils.py +162 -0
  11. AR/modules/__init__.py +0 -0
  12. AR/modules/activation.py +397 -0
  13. AR/modules/embedding.py +78 -0
  14. AR/modules/lr_schedulers.py +85 -0
  15. AR/modules/optim.py +622 -0
  16. AR/modules/patched_mha_with_cache.py +388 -0
  17. AR/modules/scaling.py +319 -0
  18. AR/modules/transformer.py +347 -0
  19. AR/text_processing/__init__.py +0 -0
  20. AR/text_processing/phonemizer.py +80 -0
  21. AR/text_processing/symbols.py +9 -0
  22. AR/utils/__init__.py +37 -0
  23. AR/utils/initialize.py +38 -0
  24. AR/utils/io.py +32 -0
  25. app.py +303 -0
  26. blue_archive/alice/alice-e15.ckpt +3 -0
  27. blue_archive/alice/alice_e8_s216.pth +3 -0
  28. blue_archive/mika/mika-e15.ckpt +3 -0
  29. blue_archive/mika/mika_e8_s176.pth +3 -0
  30. blue_archive/yuuka/yuuka-e15.ckpt +3 -0
  31. blue_archive/yuuka/yuuka_e8_s208.pth +3 -0
  32. feature_extractor/__init__.py +6 -0
  33. feature_extractor/cnhubert.py +97 -0
  34. feature_extractor/whisper_enc.py +22 -0
  35. module/__init__.py +0 -0
  36. module/attentions.py +514 -0
  37. module/commons.py +189 -0
  38. module/core_vq.py +367 -0
  39. module/data_utils.py +326 -0
  40. module/losses.py +68 -0
  41. module/mel_processing.py +111 -0
  42. module/models.py +784 -0
  43. module/modules.py +769 -0
  44. module/mrte_model.py +160 -0
  45. module/quantize.py +108 -0
  46. module/transforms.py +193 -0
  47. my_utils.py +21 -0
  48. pretrained_models/.gitattributes +35 -0
  49. pretrained_models/README.md +4 -0
  50. pretrained_models/chinese-hubert-base/config.json +72 -0
.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DUMMY1
2
+ DUMMY2
3
+ DUMMY3
4
+ logs
5
+ __pycache__
6
+ .ipynb_checkpoints
7
+ .*.swp
8
+
9
+ build
10
+ *.c
11
+ monotonic_align/monotonic_align
12
+ /.vs/vits/FileContentIndex
13
+ configs/dracu_japanese_base2.json
14
+ configs/tolove_japanese_base2.json
15
+
16
+ .idea
AR/__init__.py ADDED
File without changes
AR/data/__init__.py ADDED
File without changes
AR/data/bucket_sampler.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/bucketsampler.py
2
+ import itertools
3
+ import math
4
+ import random
5
+ from random import shuffle
6
+ from typing import Iterator
7
+ from typing import Optional
8
+ from typing import TypeVar
9
+
10
+ import torch
11
+ import torch.distributed as dist
12
+ from torch.utils.data import Dataset
13
+ from torch.utils.data import Sampler
14
+
15
+ __all__ = [
16
+ "DistributedBucketSampler",
17
+ ]
18
+
19
+ T_co = TypeVar('T_co', covariant=True)
20
+
21
+
22
+ class DistributedBucketSampler(Sampler[T_co]):
23
+ r"""
24
+ sort the dataset wrt. input length
25
+ divide samples into buckets
26
+ sort within buckets
27
+ divide buckets into batches
28
+ sort batches
29
+ """
30
+
31
+ def __init__(self,
32
+ dataset: Dataset,
33
+ num_replicas: Optional[int]=None,
34
+ rank: Optional[int]=None,
35
+ shuffle: bool=True,
36
+ seed: int=0,
37
+ drop_last: bool=False,
38
+ batch_size: int=32) -> None:
39
+ if num_replicas is None:
40
+ if not dist.is_available():
41
+ raise RuntimeError(
42
+ "Requires distributed package to be available")
43
+ num_replicas = dist.get_world_size()
44
+ if rank is None:
45
+ if not dist.is_available():
46
+ raise RuntimeError(
47
+ "Requires distributed package to be available")
48
+ rank = dist.get_rank()
49
+ torch.cuda.set_device(rank)
50
+ if rank >= num_replicas or rank < 0:
51
+ raise ValueError("Invalid rank {}, rank should be in the interval"
52
+ " [0, {}]".format(rank, num_replicas - 1))
53
+ self.dataset = dataset
54
+ self.num_replicas = num_replicas
55
+ self.rank = rank
56
+ self.epoch = 0
57
+ self.drop_last = drop_last
58
+ # If the dataset length is evenly divisible by # of replicas, then there
59
+ # is no need to drop any data, since the dataset will be split equally.
60
+ if self.drop_last and len(
61
+ self.
62
+ dataset) % self.num_replicas != 0: # type: ignore[arg-type]
63
+ # Split to nearest available length that is evenly divisible.
64
+ # This is to ensure each rank receives the same amount of data when
65
+ # using this Sampler.
66
+ self.num_samples = math.ceil(
67
+ (len(self.dataset) - self.num_replicas) /
68
+ self.num_replicas # type: ignore[arg-type]
69
+ )
70
+ else:
71
+ self.num_samples = math.ceil(
72
+ len(self.dataset) / self.num_replicas) # type: ignore[arg-type]
73
+ self.total_size = self.num_samples * self.num_replicas
74
+ self.shuffle = shuffle
75
+ self.seed = seed
76
+ self.batch_size = batch_size
77
+ self.id_with_length = self._get_sample_lengths()
78
+ self.id_buckets = self.make_buckets(bucket_width=2.0)
79
+
80
+ def _get_sample_lengths(self):
81
+ id_with_lengths = []
82
+ for i in range(len(self.dataset)):
83
+ id_with_lengths.append((i, self.dataset.get_sample_length(i)))
84
+ id_with_lengths.sort(key=lambda x: x[1])
85
+ return id_with_lengths
86
+
87
+ def make_buckets(self, bucket_width: float=2.0):
88
+ buckets = []
89
+ cur = []
90
+ max_sec = bucket_width
91
+ for id, sec in self.id_with_length:
92
+ if sec < max_sec:
93
+ cur.append(id)
94
+ else:
95
+ buckets.append(cur)
96
+ cur = [id]
97
+ max_sec += bucket_width
98
+ if len(cur) > 0:
99
+ buckets.append(cur)
100
+ return buckets
101
+
102
+ def __iter__(self) -> Iterator[T_co]:
103
+ if self.shuffle:
104
+ # deterministically shuffle based on epoch and seed
105
+ g = torch.Generator()
106
+ g.manual_seed(self.seed + self.epoch)
107
+ random.seed(self.epoch + self.seed)
108
+ shuffled_bucket = []
109
+ for buc in self.id_buckets:
110
+ buc_copy = buc.copy()
111
+ shuffle(buc_copy)
112
+ shuffled_bucket.append(buc_copy)
113
+ grouped_batch_size = self.batch_size * self.num_replicas
114
+ shuffled_bucket = list(itertools.chain(*shuffled_bucket))
115
+ n_batch = int(math.ceil(len(shuffled_bucket) / grouped_batch_size))
116
+ batches = [
117
+ shuffled_bucket[b * grouped_batch_size:(b + 1) *
118
+ grouped_batch_size] for b in range(n_batch)
119
+ ]
120
+ shuffle(batches)
121
+ indices = list(itertools.chain(*batches))
122
+ else:
123
+ # type: ignore[arg-type]
124
+ indices = list(range(len(self.dataset)))
125
+
126
+ if not self.drop_last:
127
+ # add extra samples to make it evenly divisible
128
+ padding_size = self.total_size - len(indices)
129
+ if padding_size <= len(indices):
130
+ indices += indices[:padding_size]
131
+ else:
132
+ indices += (indices * math.ceil(padding_size /
133
+ len(indices)))[:padding_size]
134
+ else:
135
+ # remove tail of data to make it evenly divisible.
136
+ indices = indices[:self.total_size]
137
+ assert len(indices) == self.total_size
138
+
139
+ # subsample
140
+ indices = indices[self.rank:self.total_size:self.num_replicas]
141
+ assert len(indices) == self.num_samples
142
+
143
+ return iter(indices)
144
+
145
+ def __len__(self) -> int:
146
+ return self.num_samples
147
+
148
+ def set_epoch(self, epoch: int) -> None:
149
+ r"""
150
+ Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
151
+ use a different random ordering for each epoch. Otherwise, the next iteration of this
152
+ sampler will yield the same ordering.
153
+
154
+ Args:
155
+ epoch (int): Epoch number.
156
+ """
157
+ self.epoch = epoch
AR/data/data_module.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/data_module.py
2
+ from pytorch_lightning import LightningDataModule
3
+ from AR.data.bucket_sampler import DistributedBucketSampler
4
+ from AR.data.dataset import Text2SemanticDataset
5
+ from torch.utils.data import DataLoader
6
+
7
+
8
+ class Text2SemanticDataModule(LightningDataModule):
9
+ def __init__(self, config, train_semantic_path, train_phoneme_path,dev_semantic_path=None, dev_phoneme_path=None):
10
+ super().__init__()
11
+ self.config = config
12
+ self.train_semantic_path = train_semantic_path
13
+ self.train_phoneme_path = train_phoneme_path
14
+ self.dev_semantic_path = dev_semantic_path
15
+ self.dev_phoneme_path = dev_phoneme_path
16
+ self.num_workers = self.config['data']['num_workers']
17
+
18
+ def prepare_data(self):
19
+ pass
20
+
21
+ def setup(self, stage=None, output_logs=False):
22
+ self._train_dataset = Text2SemanticDataset(
23
+ phoneme_path=self.train_phoneme_path,
24
+ semantic_path=self.train_semantic_path,
25
+ max_sec=self.config['data']['max_sec'],
26
+ pad_val=self.config['data']['pad_val'])
27
+ self._dev_dataset = self._train_dataset
28
+ # self._dev_dataset = Text2SemanticDataset(
29
+ # phoneme_path=self.dev_phoneme_path,
30
+ # semantic_path=self.dev_semantic_path,
31
+ # max_sample=self.config['data']['max_eval_sample'],
32
+ # max_sec=self.config['data']['max_sec'],
33
+ # pad_val=self.config['data']['pad_val'])
34
+
35
+ def train_dataloader(self):
36
+ batch_size = self.config['train']['batch_size']
37
+ sampler = DistributedBucketSampler(
38
+ self._train_dataset, batch_size=batch_size)
39
+ return DataLoader(
40
+ self._train_dataset,
41
+ batch_size=batch_size,
42
+ sampler=sampler,
43
+ collate_fn=self._train_dataset.collate,
44
+ num_workers=self.num_workers,
45
+ persistent_workers=True,
46
+ prefetch_factor=16
47
+ )
48
+
49
+ def val_dataloader(self):
50
+ return DataLoader(
51
+ self._dev_dataset,
52
+ batch_size=1,
53
+ shuffle=False,
54
+ collate_fn=self._train_dataset.collate,
55
+ num_workers=max(self.num_workers,12),
56
+ persistent_workers=True,
57
+ prefetch_factor=16
58
+ )
59
+
60
+ # 这个会使用到嘛?
61
+ def test_dataloader(self):
62
+ return DataLoader(
63
+ self._dev_dataset,
64
+ batch_size=1,
65
+ shuffle=False,
66
+ collate_fn=self._train_dataset.collate)
AR/data/dataset.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/t2s_dataset.py
2
+ import pdb
3
+ import sys
4
+ # sys.path.append("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert")
5
+ import traceback,os
6
+ from typing import Dict
7
+ from typing import List
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ import torch,json
12
+ from torch.utils.data import DataLoader
13
+ from torch.utils.data import Dataset
14
+ from transformers import AutoTokenizer
15
+
16
+ from text import cleaned_text_to_sequence
17
+ # from config import exp_dir
18
+
19
+ def batch_sequences(sequences: List[np.array], axis: int = 0, pad_value: int = 0):
20
+ seq = sequences[0]
21
+ ndim = seq.ndim
22
+ if axis < 0:
23
+ axis += ndim
24
+ dtype = seq.dtype
25
+ pad_value = dtype.type(pad_value)
26
+ seq_lengths = [seq.shape[axis] for seq in sequences]
27
+ max_length = np.max(seq_lengths)
28
+
29
+ padded_sequences = []
30
+ for seq, length in zip(sequences, seq_lengths):
31
+ padding = [(0, 0)] * axis + [(0, max_length - length)] + [(0, 0)] * (
32
+ ndim - axis - 1)
33
+ padded_seq = np.pad(
34
+ seq, padding, mode='constant', constant_values=pad_value)
35
+ padded_sequences.append(padded_seq)
36
+ batch = np.stack(padded_sequences)
37
+ return batch
38
+
39
+ class Text2SemanticDataset(Dataset):
40
+ """dataset class for text tokens to semantic model training."""
41
+
42
+ def __init__(self,
43
+ phoneme_path: str,
44
+ semantic_path: str,
45
+ max_sample: int = None,
46
+ max_sec: int = 100,
47
+ pad_val: int = 1024,
48
+ # min value of phoneme/sec
49
+ min_ps_ratio: int = 3,
50
+ # max value of phoneme/sec
51
+ max_ps_ratio: int = 25) -> None:
52
+ super().__init__()
53
+
54
+ self.semantic_data = pd.read_csv(semantic_path, delimiter='\t', encoding="utf-8")
55
+ # get dict
56
+ self.path2=phoneme_path#"%s/2-name2text.txt"%exp_dir#phoneme_path
57
+ self.path3="%s/3-bert"%(os.path.basename(phoneme_path))#"%s/3-bert"%exp_dir#bert_dir
58
+ self.path6=semantic_path#"%s/6-name2semantic.tsv"%exp_dir#semantic_path
59
+ assert os.path.exists(self.path2)
60
+ assert os.path.exists(self.path6)
61
+ self.phoneme_data={}
62
+ with open(self.path2,"r",encoding="utf8")as f:
63
+ lines=f.read().strip("\n").split("\n")
64
+
65
+ for line in lines:
66
+ tmp=line.split("\t")
67
+ if(len(tmp)!=4):continue
68
+ self.phoneme_data[tmp[0]]=[tmp[1],tmp[2],tmp[3]]
69
+
70
+ # self.phoneme_data = np.load(phoneme_path, allow_pickle=True).item()
71
+ # pad for semantic tokens
72
+ self.PAD: int = pad_val
73
+ # self.hz = 25
74
+ # with open("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert/configs/s2.json", "r") as f:data = f.read()
75
+ # data=json.loads(data)["model"]["semantic_frame_rate"]#50hz
76
+ # self.hz=int(data[:-2])#
77
+ self.hz=int(os.environ.get("hz","25hz")[:-2])
78
+
79
+ # max seconds of semantic token
80
+ self.max_sec = max_sec
81
+ self.min_ps_ratio = min_ps_ratio
82
+ self.max_ps_ratio = max_ps_ratio
83
+
84
+ if max_sample is not None:
85
+ self.semantic_data = self.semantic_data[:max_sample]
86
+
87
+ # {idx: (semantic, phoneme)}
88
+ # semantic list, phoneme list
89
+ self.semantic_phoneme = []
90
+ self.item_names = []
91
+
92
+ self.inited = False
93
+
94
+ if not self.inited:
95
+ # 调用初始化函数
96
+ self.init_batch()
97
+ self.inited = True
98
+ del self.semantic_data
99
+ del self.phoneme_data
100
+ # self.tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext-large")
101
+ # self.tokenizer = AutoTokenizer.from_pretrained("/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large")
102
+
103
+
104
+ def init_batch(self):
105
+ semantic_data_len = len(self.semantic_data)
106
+ phoneme_data_len = len(self.phoneme_data.keys())
107
+ print("semantic_data_len:", semantic_data_len)
108
+ print("phoneme_data_len:", phoneme_data_len)
109
+ idx = 0
110
+ num_not_in = 0
111
+ num_deleted_bigger = 0
112
+ num_deleted_ps = 0
113
+ for i in range(semantic_data_len):
114
+ # 先依次遍历
115
+ # get str
116
+ item_name = self.semantic_data['item_name'][i]
117
+ # print(self.phoneme_data)
118
+ try:
119
+ phoneme, word2ph, text = self.phoneme_data[item_name]
120
+ except Exception:
121
+ traceback.print_exc()
122
+ # print(f"{item_name} not in self.phoneme_data !")
123
+ num_not_in += 1
124
+ continue
125
+
126
+ semantic_str = self.semantic_data['semantic_audio'][i]
127
+ # get token list
128
+ semantic_ids = [int(idx) for idx in semantic_str.split(' ')]
129
+ # (T), 是否需要变成 (1, T) -> 不需要,因为需要求 len
130
+ # 过滤掉太长的样本
131
+ if len(semantic_ids) > self.max_sec * self.hz:#########1###根据token���数推测总时长过滤时长60s(config里)#40*25=1k
132
+ num_deleted_bigger += 1
133
+ continue
134
+ # (T, ), 这个速度不会很慢,所以可以在一开始就处理,无需在 __getitem__ 里面单个处理####
135
+ phoneme = phoneme.split(' ')
136
+
137
+ try:
138
+ phoneme_ids = cleaned_text_to_sequence(phoneme)
139
+ except:
140
+ traceback.print_exc()
141
+ # print(f"{item_name} not in self.phoneme_data !")
142
+ num_not_in += 1
143
+ continue
144
+ # if len(phoneme_ids) >400:###########2:改为恒定限制为semantic/2.5就行
145
+ if len(phoneme_ids) >self.max_sec * self.hz/2.5:###########2:改为恒定限制为semantic/2.5就行
146
+ num_deleted_ps += 1
147
+ continue
148
+ # if len(semantic_ids) > 1000:###########3
149
+ # num_deleted_bigger += 1
150
+ # continue
151
+
152
+ ps_ratio = len(phoneme_ids) / (len(semantic_ids) / self.hz)
153
+
154
+ if ps_ratio > self.max_ps_ratio or ps_ratio < self.min_ps_ratio:##########4#3~25#每秒多少个phone
155
+ num_deleted_ps += 1
156
+ # print(item_name)
157
+ continue
158
+
159
+ self.semantic_phoneme.append((semantic_ids, phoneme_ids))
160
+ idx += 1
161
+ self.item_names.append(item_name)
162
+
163
+ min_num=100#20直接不补#30补了也不存ckpt
164
+ leng =len(self.semantic_phoneme)
165
+ if(leng<min_num):
166
+ tmp1=self.semantic_phoneme
167
+ tmp2=self.item_names
168
+ self.semantic_phoneme=[]
169
+ self.item_names=[]
170
+ for _ in range(max(2,int(min_num/leng))):
171
+ self.semantic_phoneme+=tmp1
172
+ self.item_names+=tmp2
173
+ if num_not_in > 0:
174
+ print(f"there are {num_not_in} semantic datas not in phoneme datas")
175
+ if num_deleted_bigger > 0:
176
+ print(
177
+ f"deleted {num_deleted_bigger} audios who's duration are bigger than {self.max_sec} seconds"
178
+ )
179
+ if num_deleted_ps > 0:
180
+ # 4702 for LibriTTS, LirbriTTS 是标注数据, 是否需要筛?=> 需要,有值为 100 的极端值
181
+ print(
182
+ f"deleted {num_deleted_ps} audios who's phoneme/sec are bigger than {self.max_ps_ratio} or smaller than {self.min_ps_ratio}"
183
+ )
184
+ '''
185
+ there are 31 semantic datas not in phoneme datas
186
+ deleted 34 audios who's duration are bigger than 54 seconds
187
+ deleted 3190 audios who's phoneme/sec are bigger than 25 or smaller than 3
188
+ dataset.__len__(): 366463
189
+
190
+ '''
191
+ # 345410 for LibriTTS
192
+ print("dataset.__len__():", self.__len__())
193
+
194
+ def __get_item_names__(self) -> List[str]:
195
+ return self.item_names
196
+
197
+ def __len__(self) -> int:
198
+ return len(self.semantic_phoneme)
199
+
200
+ def __getitem__(self, idx: int) -> Dict:
201
+ semantic_ids, phoneme_ids = self.semantic_phoneme[idx]
202
+ item_name = self.item_names[idx]
203
+ phoneme_ids_len = len(phoneme_ids)
204
+ # semantic tokens target
205
+ semantic_ids_len = len(semantic_ids)
206
+
207
+ flag=0
208
+ path_bert = "%s/%s.pt" % (self.path3, item_name)
209
+ if(os.path.exists(path_bert)==True):bert_feature = torch.load(path_bert,map_location="cpu")
210
+ else:flag=1
211
+ if(flag==1):
212
+ # bert_feature=torch.zeros_like(phoneme_ids,dtype=torch.float32)
213
+ bert_feature=None
214
+ else:
215
+ assert bert_feature.shape[-1] == len(phoneme_ids)
216
+ return {
217
+ 'idx': idx,
218
+ 'phoneme_ids': phoneme_ids,
219
+ 'phoneme_ids_len': phoneme_ids_len,
220
+ 'semantic_ids': semantic_ids,
221
+ 'semantic_ids_len': semantic_ids_len,
222
+ 'bert_feature': bert_feature,
223
+ }
224
+
225
+ def get_sample_length(self, idx: int):
226
+ semantic_ids = self.semantic_phoneme[idx][0]
227
+ sec = 1.0 * len(semantic_ids) / self.hz
228
+ return sec
229
+
230
+ def collate(self, examples: List[Dict]) -> Dict:
231
+ sample_index: List[int] = []
232
+ phoneme_ids: List[torch.Tensor] = []
233
+ phoneme_ids_lens: List[int] = []
234
+ semantic_ids: List[torch.Tensor] = []
235
+ semantic_ids_lens: List[int] = []
236
+ # return
237
+
238
+
239
+ for item in examples:
240
+ sample_index.append(item["idx"])
241
+ phoneme_ids.append(np.array(item["phoneme_ids"], dtype=np.int64))
242
+ semantic_ids.append(np.array(item["semantic_ids"], dtype=np.int64))
243
+ phoneme_ids_lens.append(item["phoneme_ids_len"])
244
+ semantic_ids_lens.append(item["semantic_ids_len"])
245
+
246
+ # pad 0
247
+ phoneme_ids = batch_sequences(phoneme_ids)
248
+ semantic_ids = batch_sequences(semantic_ids, pad_value=self.PAD)
249
+
250
+ # # convert each batch to torch.tensor
251
+ phoneme_ids = torch.tensor(phoneme_ids)
252
+ semantic_ids = torch.tensor(semantic_ids)
253
+ phoneme_ids_lens = torch.tensor(phoneme_ids_lens)
254
+ semantic_ids_lens = torch.tensor(semantic_ids_lens)
255
+ bert_padded = torch.FloatTensor(len(examples), 1024, max(phoneme_ids_lens))
256
+ bert_padded.zero_()
257
+
258
+ for idx, item in enumerate(examples):
259
+ bert = item['bert_feature']
260
+ if(bert!=None):
261
+ bert_padded[idx, :, :bert.shape[-1]] = bert
262
+
263
+ return {
264
+ # List[int]
265
+ "ids": sample_index,
266
+ # torch.Tensor (B, max_phoneme_length)
267
+ "phoneme_ids": phoneme_ids,
268
+ # torch.Tensor (B)
269
+ "phoneme_ids_len": phoneme_ids_lens,
270
+ # torch.Tensor (B, max_semantic_ids_length)
271
+ "semantic_ids": semantic_ids,
272
+ # torch.Tensor (B)
273
+ "semantic_ids_len": semantic_ids_lens,
274
+ # torch.Tensor (B, 1024, max_phoneme_length)
275
+ "bert_feature": bert_padded,
276
+ }
277
+
278
+
279
+ if __name__ == '__main__':
280
+ root_dir = '/data/docker/liujing04/gpt-vits/prepare/dump_mix/'
281
+ dataset = Text2SemanticDataset(
282
+ phoneme_path=root_dir + 'phoneme_train.npy',
283
+ semantic_path=root_dir + 'semantic_train.tsv')
284
+
285
+ batch_size = 12
286
+ dataloader = DataLoader(
287
+ dataset,
288
+ batch_size=batch_size,
289
+ collate_fn=dataset.collate,
290
+ shuffle=False)
291
+ for i, batch in enumerate(dataloader):
292
+ if(i%1000==0):print(i)
293
+ # if i == 0:
294
+ # print('batch["ids"]:', batch["ids"])
295
+ # print('batch["phoneme_ids"]:', batch["phoneme_ids"],
296
+ # batch["phoneme_ids"].shape)
297
+ # print('batch["phoneme_ids_len"]:', batch["phoneme_ids_len"],
298
+ # batch["phoneme_ids_len"].shape)
299
+ # print('batch["semantic_ids"]:', batch["semantic_ids"],
300
+ # batch["semantic_ids"].shape)
301
+ # print('batch["semantic_ids_len"]:', batch["semantic_ids_len"],
302
+ # batch["semantic_ids_len"].shape)
AR/models/__init__.py ADDED
File without changes
AR/models/t2s_lightning_module.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/model/t2s_lightning_module.py
2
+ import os,sys
3
+ now_dir = os.getcwd()
4
+ sys.path.append(now_dir)
5
+ from typing import Dict
6
+
7
+ import torch
8
+ from pytorch_lightning import LightningModule
9
+ from AR.models.t2s_model import Text2SemanticDecoder
10
+ from AR.modules.lr_schedulers import WarmupCosineLRSchedule
11
+ from AR.modules.optim import ScaledAdam
12
+
13
+
14
+ class Text2SemanticLightningModule(LightningModule):
15
+ def __init__(self, config, output_dir,is_train=True):
16
+ super().__init__()
17
+ self.config = config
18
+ self.top_k = 3
19
+ self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
20
+ pretrained_s1=config.get("pretrained_s1")
21
+ if(pretrained_s1 and is_train):
22
+ # print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
23
+ print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["weight"]))
24
+ if is_train:
25
+ self.automatic_optimization = False
26
+ self.save_hyperparameters()
27
+ self.eval_dir = output_dir / 'eval'
28
+ self.eval_dir.mkdir(parents=True, exist_ok=True)
29
+
30
+ def training_step(self, batch: Dict, batch_idx: int):
31
+
32
+ opt = self.optimizers()
33
+ scheduler = self.lr_schedulers()
34
+ loss, acc = self.model.forward(
35
+ batch['phoneme_ids'], batch['phoneme_ids_len'],
36
+ batch['semantic_ids'], batch['semantic_ids_len'],
37
+ batch['bert_feature'])
38
+ self.manual_backward(loss)
39
+ if batch_idx > 0 and batch_idx % 4 == 0:
40
+ opt.step()
41
+ opt.zero_grad()
42
+ scheduler.step()
43
+
44
+ self.log(
45
+ "total_loss",
46
+ loss,
47
+ on_step=True,
48
+ on_epoch=True,
49
+ prog_bar=True,
50
+ sync_dist=True)
51
+ self.log(
52
+ "lr",
53
+ scheduler.get_last_lr()[0],
54
+ on_epoch=True,
55
+ prog_bar=True,
56
+ sync_dist=True)
57
+ self.log(
58
+ f"top_{self.top_k}_acc",
59
+ acc,
60
+ on_step=True,
61
+ on_epoch=True,
62
+ prog_bar=True,
63
+ sync_dist=True)
64
+
65
+ def validation_step(self, batch: Dict, batch_idx: int):return
66
+ # # get loss
67
+ # loss, acc = self.model.forward(
68
+ # batch['phoneme_ids'], batch['phoneme_ids_len'],
69
+ # batch['semantic_ids'], batch['semantic_ids_len'],
70
+ # batch['bert_feature']
71
+ # )
72
+ #
73
+ # self.log(
74
+ # "val_total_loss",
75
+ # loss,
76
+ # on_step=True,
77
+ # on_epoch=True,
78
+ # prog_bar=True,
79
+ # sync_dist=True)
80
+ # self.log(
81
+ # f"val_top_{self.top_k}_acc",
82
+ # acc,
83
+ # on_step=True,
84
+ # on_epoch=True,
85
+ # prog_bar=True,
86
+ # sync_dist=True)
87
+ #
88
+ # # get infer output
89
+ # semantic_len = batch['semantic_ids'].size(1)
90
+ # prompt_len = min(int(semantic_len * 0.5), 150)
91
+ # prompt = batch['semantic_ids'][:, :prompt_len]
92
+ # pred_semantic = self.model.infer(batch['phoneme_ids'],
93
+ # batch['phoneme_ids_len'], prompt,
94
+ # batch['bert_feature']
95
+ # )
96
+ # save_name = f'semantic_toks_{batch_idx}.pt'
97
+ # save_path = os.path.join(self.eval_dir, save_name)
98
+ # torch.save(pred_semantic.detach().cpu(), save_path)
99
+
100
+ def configure_optimizers(self):
101
+ model_parameters = self.model.parameters()
102
+ parameters_names = []
103
+ parameters_names.append([
104
+ name_param_pair[0]
105
+ for name_param_pair in self.model.named_parameters()
106
+ ])
107
+ lm_opt = ScaledAdam(
108
+ model_parameters,
109
+ lr=0.01,
110
+ betas=(0.9, 0.95),
111
+ clipping_scale=2.0,
112
+ parameters_names=parameters_names,
113
+ show_dominant_parameters=False,
114
+ clipping_update_period=1000, )
115
+
116
+ return {
117
+ "optimizer": lm_opt,
118
+ "lr_scheduler": {
119
+ "scheduler":
120
+ WarmupCosineLRSchedule(
121
+ lm_opt,
122
+ init_lr=self.config['optimizer']['lr_init'],
123
+ peak_lr=self.config['optimizer']['lr'],
124
+ end_lr=self.config['optimizer']['lr_end'],
125
+ warmup_steps=self.config['optimizer']['warmup_steps'],
126
+ total_steps=self.config['optimizer']['decay_steps'])
127
+ }
128
+ }
AR/models/t2s_model.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/model/t2s_model.py
2
+ import torch
3
+ from tqdm import tqdm
4
+
5
+ from AR.models.utils import make_pad_mask
6
+ from AR.models.utils import topk_sampling,sample,logits_to_probs,multinomial_sample_one_no_sync
7
+ from AR.modules.embedding import SinePositionalEmbedding
8
+ from AR.modules.embedding import TokenEmbedding
9
+ from AR.modules.transformer import LayerNorm
10
+ from AR.modules.transformer import TransformerEncoder
11
+ from AR.modules.transformer import TransformerEncoderLayer
12
+ from torch import nn
13
+ from torch.nn import functional as F
14
+ from torchmetrics.classification import MulticlassAccuracy
15
+
16
+ default_config = {
17
+ "embedding_dim": 512,
18
+ "hidden_dim": 512,
19
+ "num_head": 8,
20
+ "num_layers": 12,
21
+ "num_codebook": 8,
22
+ "p_dropout": 0.0,
23
+ "vocab_size": 1024 + 1,
24
+ "phoneme_vocab_size": 512,
25
+ "EOS": 1024
26
+ }
27
+
28
+
29
+ class Text2SemanticDecoder(nn.Module):
30
+ def __init__(self, config, norm_first=False, top_k=3):
31
+ super(Text2SemanticDecoder, self).__init__()
32
+ self.model_dim = config['model']["hidden_dim"]
33
+ self.embedding_dim = config['model']["embedding_dim"]
34
+ self.num_head = config['model']["head"]
35
+ self.num_layers = config['model']["n_layer"]
36
+ self.norm_first = norm_first
37
+ self.vocab_size = config['model']["vocab_size"]
38
+ self.phoneme_vocab_size = config['model']["phoneme_vocab_size"]
39
+ self.p_dropout = config['model']["dropout"]
40
+ self.EOS = config['model']["EOS"]
41
+ self.norm_first = norm_first
42
+ assert self.EOS == self.vocab_size - 1
43
+ # should be same as num of kmeans bin
44
+ # assert self.EOS == 1024
45
+ self.bert_proj = nn.Linear(1024, self.embedding_dim)
46
+ self.ar_text_embedding = TokenEmbedding(
47
+ self.embedding_dim, self.phoneme_vocab_size, self.p_dropout)
48
+ self.ar_text_position = SinePositionalEmbedding(
49
+ self.embedding_dim, dropout=0.1, scale=False, alpha=True)
50
+ self.ar_audio_embedding = TokenEmbedding(
51
+ self.embedding_dim, self.vocab_size, self.p_dropout)
52
+ self.ar_audio_position = SinePositionalEmbedding(
53
+ self.embedding_dim, dropout=0.1, scale=False, alpha=True)
54
+
55
+ self.h = TransformerEncoder(
56
+ TransformerEncoderLayer(
57
+ d_model=self.model_dim,
58
+ nhead=self.num_head,
59
+ dim_feedforward=self.model_dim * 4,
60
+ dropout=0.1,
61
+ batch_first=True,
62
+ norm_first=norm_first, ),
63
+ num_layers=self.num_layers,
64
+ norm=LayerNorm(self.model_dim) if norm_first else None, )
65
+
66
+ self.ar_predict_layer = nn.Linear(
67
+ self.model_dim, self.vocab_size, bias=False)
68
+ self.loss_fct = nn.CrossEntropyLoss(reduction='sum')
69
+
70
+ self.ar_accuracy_metric = MulticlassAccuracy(
71
+ self.vocab_size,
72
+ top_k=top_k,
73
+ average="micro",
74
+ multidim_average="global",
75
+ ignore_index=self.EOS, )
76
+
77
+ def forward(self, x, x_lens, y, y_lens, bert_feature):
78
+ '''
79
+ x: phoneme_ids
80
+ y: semantic_ids
81
+ '''
82
+ x = self.ar_text_embedding(x)
83
+ x = x + self.bert_proj(bert_feature.transpose(1,2))
84
+ x = self.ar_text_position(x)
85
+ x_mask = make_pad_mask(x_lens)
86
+
87
+ y_mask = make_pad_mask(y_lens)
88
+ y_mask_int = y_mask.type(torch.int64)
89
+ codes = y.type(torch.int64) * (1 - y_mask_int)
90
+
91
+ # Training
92
+ # AR Decoder
93
+ y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
94
+ x_len = x_lens.max()
95
+ y_len = y_lens.max()
96
+ y_emb = self.ar_audio_embedding(y)
97
+ y_pos = self.ar_audio_position(y_emb)
98
+
99
+ xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
100
+ ar_xy_padding_mask = xy_padding_mask
101
+
102
+ x_attn_mask = F.pad(
103
+ torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
104
+ (0, y_len),
105
+ value=True, )
106
+ y_attn_mask = F.pad(
107
+ torch.triu(
108
+ torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
109
+ diagonal=1, ),
110
+ (x_len, 0),
111
+ value=False, )
112
+ xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
113
+ bsz, src_len = x.shape[0], x_len + y_len
114
+ _xy_padding_mask = (ar_xy_padding_mask.view(bsz, 1, 1, src_len)
115
+ .expand(-1, self.num_head, -1, -1)
116
+ .reshape(bsz * self.num_head, 1, src_len))
117
+ xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
118
+ new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
119
+ new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
120
+ xy_attn_mask = new_attn_mask
121
+ # x 和完整的 y 一次性输入模型
122
+ xy_pos = torch.concat([x, y_pos], dim=1)
123
+ xy_dec, _ = self.h(
124
+ (xy_pos, None),
125
+ mask=xy_attn_mask, )
126
+ logits = self.ar_predict_layer(xy_dec[:, x_len:]).permute(0, 2, 1)
127
+ # loss
128
+ # from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
129
+ loss = F.cross_entropy(logits, targets, reduction='sum')
130
+ acc = self.ar_accuracy_metric(logits.detach(), targets).item()
131
+ return loss, acc
132
+
133
+ # 需要看下这个函数和 forward 的区别以及没有 semantic 的时候 prompts 输入什么
134
+ def infer(self,
135
+ x,
136
+ x_lens,
137
+ prompts,
138
+ bert_feature,
139
+ top_k: int=-100,
140
+ early_stop_num: int=-1,
141
+ temperature: float=1.0):
142
+
143
+ x = self.ar_text_embedding(x)
144
+ x = x + self.bert_proj(bert_feature.transpose(1,2))
145
+ x = self.ar_text_position(x)
146
+
147
+ # AR Decoder
148
+ y = prompts
149
+ prefix_len = y.shape[1]
150
+ x_len = x.shape[1]
151
+ x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
152
+ stop = False
153
+ for _ in tqdm(range(1500)):
154
+ y_emb = self.ar_audio_embedding(y)
155
+ y_pos = self.ar_audio_position(y_emb)
156
+ # x 和逐渐增长的 y 一起输入给模型
157
+ xy_pos = torch.concat([x, y_pos], dim=1)
158
+ y_len = y.shape[1]
159
+ x_attn_mask_pad = F.pad(
160
+ x_attn_mask,
161
+ (0, y_len),
162
+ value=True, )
163
+ y_attn_mask = F.pad(
164
+ torch.triu(
165
+ torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
166
+ (x_len, 0),
167
+ value=False, )
168
+ xy_attn_mask = torch.concat(
169
+ [x_attn_mask_pad, y_attn_mask], dim=0).to(y.device)
170
+
171
+ xy_dec, _ = self.h(
172
+ (xy_pos, None),
173
+ mask=xy_attn_mask, )
174
+ logits = self.ar_predict_layer(xy_dec[:, -1])
175
+ samples = topk_sampling(
176
+ logits, top_k=top_k, top_p=1.0, temperature=temperature)
177
+
178
+ if early_stop_num != -1 and (y.shape[1] - prefix_len
179
+ ) > early_stop_num:
180
+ print("use early stop num:", early_stop_num)
181
+ stop = True
182
+
183
+ if torch.argmax(
184
+ logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
185
+ # print(torch.argmax(logits, dim=-1)[0] == self.EOS, samples[0, 0] == self.EOS)
186
+ stop = True
187
+ if stop:
188
+ if prompts.shape[1] == y.shape[1]:
189
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
190
+ print('bad zero prediction')
191
+ print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
192
+ break
193
+ # 本次生成的 semantic_ids 和之前的 y 构成新的 y
194
+ # print(samples.shape)#[1,1]#第一个1是bs
195
+ # import os
196
+ # os._exit(2333)
197
+ y = torch.concat([y, samples], dim=1)
198
+ return y
199
+
200
+ def pad_y_eos(self, y, y_mask_int, eos_id):
201
+ targets = F.pad(
202
+ y, (0, 1), value=0) + eos_id * F.pad(
203
+ y_mask_int, (0, 1), value=1)
204
+ # 错位
205
+ return targets[:, :-1], targets[:, 1:]
206
+
207
+ def infer_panel(self,
208
+ x,#####全部文本token
209
+ x_lens,
210
+ prompts,####参考音频token
211
+ bert_feature,
212
+ top_k: int=-100,
213
+ early_stop_num: int=-1,
214
+ temperature: float=1.0):
215
+
216
+ x = self.ar_text_embedding(x)
217
+ x = x + self.bert_proj(bert_feature.transpose(1,2))
218
+ x = self.ar_text_position(x)
219
+
220
+ # AR Decoder
221
+ y = prompts
222
+ prefix_len = y.shape[1]
223
+ x_len = x.shape[1]
224
+ x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
225
+ stop = False
226
+ # print(1111111,self.num_layers)
227
+ cache={
228
+ "all_stage":self.num_layers,
229
+ "k":[None]*self.num_layers,###根据配置自己手写
230
+ "v":[None]*self.num_layers,
231
+ # "xy_pos":None,##y_pos位置编码每次都不一样的没法缓存,每次都要重新拼xy_pos.主要还是写法原因,其实是可以历史统一一样的,但也没啥计算量就不管了
232
+ "y_emb":None,##只需要对最新的samples求emb,再拼历史的就行
233
+ # "logits":None,###原版就已经只对结尾求再拼接了,不用管
234
+ # "xy_dec":None,###不需要,本来只需要最后一个做logits
235
+ "first_infer":1,
236
+ "stage":0
237
+ }
238
+ for idx in tqdm(range(1500)):
239
+ if(cache["first_infer"]==1):
240
+ y_emb = self.ar_audio_embedding(y)
241
+ else:
242
+ y_emb = torch.cat([cache["y_emb"],self.ar_audio_embedding(y[:,-1:])],1)
243
+ cache["y_emb"]=y_emb
244
+ y_pos = self.ar_audio_position(y_emb)
245
+ # x 和逐渐增长的 y 一起输入给模型
246
+ if(cache["first_infer"]==1):
247
+ xy_pos = torch.concat([x, y_pos], dim=1)
248
+ else:
249
+ xy_pos=y_pos[:,-1:]
250
+ y_len = y_pos.shape[1]
251
+ ###以下3个不做缓存
252
+ if (cache["first_infer"] == 1):
253
+ x_attn_mask_pad = F.pad(
254
+ x_attn_mask,
255
+ (0, y_len),###xx的纯0扩展到xx纯0+xy纯1,(x,x+y)
256
+ value=True, )
257
+ y_attn_mask = F.pad(###yy的右上1扩展到左边xy的0,(y,x+y)
258
+ torch.triu(
259
+ torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
260
+ (x_len, 0),
261
+ value=False, )
262
+ xy_attn_mask = torch.concat(
263
+ [x_attn_mask_pad, y_attn_mask], dim=0).to(y.device)
264
+ else:
265
+ ###最右边一列(是错的)
266
+ # xy_attn_mask=torch.ones((1, x_len+y_len), dtype=torch.bool,device=xy_pos.device)
267
+ # xy_attn_mask[:,-1]=False
268
+ ###最下面一行(是对的)
269
+ xy_attn_mask = torch.zeros((1, x_len + y_len), dtype=torch.bool, device=xy_pos.device)
270
+ # pdb.set_trace()
271
+ ###缓存重头戏
272
+ # print(1111,xy_pos.shape,xy_attn_mask.shape,x_len,y_len)
273
+ xy_dec, _ = self.h(
274
+ (xy_pos, None),
275
+ mask=xy_attn_mask,cache=cache )
276
+ logits = self.ar_predict_layer(xy_dec[:, -1])##不用改,如果用了cache的默认就是只有一帧,取最后一帧一样的
277
+ # samples = topk_sampling(logits, top_k=top_k, top_p=1.0, temperature=temperature)
278
+ samples = sample(logits[0], y, top_k=top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
279
+ if early_stop_num != -1 and (y.shape[1] - prefix_len
280
+ ) > early_stop_num:
281
+ print("use early stop num:", early_stop_num)
282
+ stop = True
283
+
284
+ if torch.argmax(
285
+ logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
286
+ # print(torch.argmax(logits, dim=-1)[0] == self.EOS, samples[0, 0] == self.EOS)
287
+ stop = True
288
+ if stop:
289
+ if prompts.shape[1] == y.shape[1]:
290
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
291
+ print('bad zero prediction')
292
+ print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
293
+ break
294
+ # 本次生成的 semantic_ids 和之前的 y 构成新的 y
295
+ # print(samples.shape)#[1,1]#第一个1是bs
296
+ y = torch.concat([y, samples], dim=1)
297
+ cache["first_infer"]=0
298
+ return y,idx
AR/models/utils.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/model/utils.py\
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+ def sequence_mask(length, max_length=None):
6
+ if max_length is None:
7
+ max_length = length.max()
8
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
9
+ return x.unsqueeze(0) < length.unsqueeze(1)
10
+
11
+
12
+ def make_pad_mask(lengths: torch.Tensor, max_len: int=0) -> torch.Tensor:
13
+ """
14
+ Args:
15
+ lengths:
16
+ A 1-D tensor containing sentence lengths.
17
+ max_len:
18
+ The length of masks.
19
+ Returns:
20
+ Return a 2-D bool tensor, where masked positions
21
+ are filled with `True` and non-masked positions are
22
+ filled with `False`.
23
+
24
+ #>>> lengths = torch.tensor([1, 3, 2, 5])
25
+ #>>> make_pad_mask(lengths)
26
+ tensor([[False, True, True, True, True],
27
+ [False, False, False, True, True],
28
+ [False, False, True, True, True],
29
+ [False, False, False, False, False]])
30
+ """
31
+ assert lengths.ndim == 1, lengths.ndim
32
+ max_len = max(max_len, lengths.max())
33
+ n = lengths.size(0)
34
+ seq_range = torch.arange(0, max_len, device=lengths.device)
35
+ expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)
36
+
37
+ return expaned_lengths >= lengths.unsqueeze(-1)
38
+
39
+
40
+ # https://github.com/microsoft/unilm/blob/master/xtune/src/transformers/modeling_utils.py
41
+ def top_k_top_p_filtering(logits,
42
+ top_k=0,
43
+ top_p=1.0,
44
+ filter_value=-float("Inf"),
45
+ min_tokens_to_keep=1):
46
+ """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
47
+ Args:
48
+ logits: logits distribution shape (batch size, vocabulary size)
49
+ if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
50
+ if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
51
+ Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
52
+ Make sure we keep at least min_tokens_to_keep per batch example in the output
53
+ From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
54
+ """
55
+ if top_k > 0:
56
+ top_k = min(max(top_k, min_tokens_to_keep),
57
+ logits.size(-1)) # Safety check
58
+ # Remove all tokens with a probability less than the last token of the top-k
59
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
60
+ logits[indices_to_remove] = filter_value
61
+
62
+ if top_p < 1.0:
63
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
64
+ cumulative_probs = torch.cumsum(
65
+ F.softmax(sorted_logits, dim=-1), dim=-1)
66
+
67
+ # Remove tokens with cumulative probability above the threshold (token with 0 are kept)
68
+ sorted_indices_to_remove = cumulative_probs > top_p
69
+ if min_tokens_to_keep > 1:
70
+ # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
71
+ sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
72
+ # Shift the indices to the right to keep also the first token above the threshold
73
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[
74
+ ..., :-1].clone()
75
+ sorted_indices_to_remove[..., 0] = 0
76
+
77
+ # scatter sorted tensors to original indexing
78
+ indices_to_remove = sorted_indices_to_remove.scatter(
79
+ 1, sorted_indices, sorted_indices_to_remove)
80
+ logits[indices_to_remove] = filter_value
81
+ return logits
82
+
83
+
84
+ def topk_sampling(logits, top_k=10, top_p=1.0, temperature=1.0):
85
+ # temperature: (`optional`) float
86
+ # The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.
87
+ # top_k: (`optional`) int
88
+ # The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.
89
+ # top_p: (`optional`) float
90
+ # The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.
91
+
92
+ # Temperature (higher temperature => more likely to sample low probability tokens)
93
+ if temperature != 1.0:
94
+ logits = logits / temperature
95
+ # Top-p/top-k filtering
96
+ logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
97
+ # Sample
98
+ token = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
99
+ return token
100
+
101
+
102
+ from typing import Optional, Tuple
103
+ def multinomial_sample_one_no_sync(
104
+ probs_sort,
105
+ ): # Does multinomial sampling without a cuda synchronization
106
+ q = torch.empty_like(probs_sort).exponential_(1)
107
+ return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
108
+
109
+
110
+ def logits_to_probs(
111
+ logits,
112
+ previous_tokens: Optional[torch.Tensor] = None,
113
+ temperature: float = 1.0,
114
+ top_k: Optional[int] = None,
115
+ top_p: Optional[int] = None,
116
+ repetition_penalty: float = 1.0,
117
+ ):
118
+ previous_tokens=previous_tokens.squeeze()
119
+ # print(logits.shape,previous_tokens.shape)
120
+ # pdb.set_trace()
121
+ if previous_tokens is not None and repetition_penalty != 1.0:
122
+ previous_tokens = previous_tokens.long()
123
+ score = torch.gather(logits, dim=0, index=previous_tokens)
124
+ score = torch.where(
125
+ score < 0, score * repetition_penalty, score / repetition_penalty
126
+ )
127
+ logits.scatter_(dim=0, index=previous_tokens, src=score)
128
+
129
+ if top_p is not None and top_p < 1.0:
130
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
131
+ cum_probs = torch.cumsum(
132
+ torch.nn.functional.softmax(sorted_logits, dim=-1), dim=-1
133
+ )
134
+ sorted_indices_to_remove = cum_probs > top_p
135
+ sorted_indices_to_remove[0] = False # keep at least one option
136
+ indices_to_remove = sorted_indices_to_remove.scatter(
137
+ dim=0, index=sorted_indices, src=sorted_indices_to_remove
138
+ )
139
+ logits = logits.masked_fill(indices_to_remove, -float("Inf"))
140
+
141
+ logits = logits / max(temperature, 1e-5)
142
+
143
+ if top_k is not None:
144
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
145
+ pivot = v.select(-1, -1).unsqueeze(-1)
146
+ logits = torch.where(logits < pivot, -float("Inf"), logits)
147
+
148
+ probs = torch.nn.functional.softmax(logits, dim=-1)
149
+ return probs
150
+
151
+
152
+ def sample(
153
+ logits,
154
+ previous_tokens: Optional[torch.Tensor] = None,
155
+ **sampling_kwargs,
156
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
157
+ probs = logits_to_probs(
158
+ logits=logits, previous_tokens=previous_tokens, **sampling_kwargs
159
+ )
160
+ idx_next = multinomial_sample_one_no_sync(probs)
161
+ return idx_next, probs
162
+
AR/modules/__init__.py ADDED
File without changes
AR/modules/activation.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
2
+ from typing import Optional
3
+ from typing import Tuple
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn import Linear
7
+ from torch.nn import Module
8
+ from torch.nn.init import constant_
9
+ from torch.nn.init import xavier_normal_
10
+ from torch.nn.init import xavier_uniform_
11
+ from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
12
+ from torch.nn.parameter import Parameter
13
+
14
+ from torch.nn import functional as F
15
+ from AR.modules.patched_mha_with_cache import multi_head_attention_forward_patched
16
+ F.multi_head_attention_forward=multi_head_attention_forward_patched
17
+
18
+ class MultiheadAttention(Module):
19
+ r"""Allows the model to jointly attend to information
20
+ from different representation subspaces as described in the paper:
21
+ `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
22
+
23
+ Multi-Head Attention is defined as:
24
+
25
+ .. math::
26
+ \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
27
+
28
+ where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
29
+
30
+ ``forward()`` will use a special optimized implementation if all of the following
31
+ conditions are met:
32
+
33
+ - self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor. This
34
+ restriction will be loosened in the future.)
35
+ - Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
36
+ - training is disabled (using ``.eval()``)
37
+ - dropout is 0
38
+ - ``add_bias_kv`` is ``False``
39
+ - ``add_zero_attn`` is ``False``
40
+ - ``batch_first`` is ``True`` and the input is batched
41
+ - ``kdim`` and ``vdim`` are equal to ``embed_dim``
42
+ - at most one of ``key_padding_mask`` or ``attn_mask`` is passed
43
+ - if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
44
+ nor ``attn_mask`` is passed
45
+
46
+ If the optimized implementation is in use, a
47
+ `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
48
+ ``query``/``key``/``value`` to represent padding more efficiently than using a
49
+ padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
50
+ will be returned, and an additional speedup proportional to the fraction of the input
51
+ that is padding can be expected.
52
+
53
+ Args:
54
+ embed_dim: Total dimension of the model.
55
+ num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
56
+ across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
57
+ dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
58
+ bias: If specified, adds bias to input / output projection layers. Default: ``True``.
59
+ add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
60
+ add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
61
+ Default: ``False``.
62
+ kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
63
+ vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
64
+ batch_first: If ``True``, then the input and output tensors are provided
65
+ as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
66
+
67
+ Examples::
68
+
69
+ >>> # xdoctest: +SKIP
70
+ >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
71
+ >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
72
+
73
+ """
74
+ __constants__ = ["batch_first"]
75
+ bias_k: Optional[torch.Tensor]
76
+ bias_v: Optional[torch.Tensor]
77
+
78
+ def __init__(
79
+ self,
80
+ embed_dim,
81
+ num_heads,
82
+ dropout=0.0,
83
+ bias=True,
84
+ add_bias_kv=False,
85
+ add_zero_attn=False,
86
+ kdim=None,
87
+ vdim=None,
88
+ batch_first=False,
89
+ linear1_cls=Linear,
90
+ linear2_cls=Linear,
91
+ device=None,
92
+ dtype=None, ) -> None:
93
+ factory_kwargs = {"device": device, "dtype": dtype}
94
+ super(MultiheadAttention, self).__init__()
95
+ self.embed_dim = embed_dim
96
+ self.kdim = kdim if kdim is not None else embed_dim
97
+ self.vdim = vdim if vdim is not None else embed_dim
98
+ self._qkv_same_embed_dim = (self.kdim == embed_dim and
99
+ self.vdim == embed_dim)
100
+
101
+ self.num_heads = num_heads
102
+ self.dropout = dropout
103
+ self.batch_first = batch_first
104
+ self.head_dim = embed_dim // num_heads
105
+ assert (self.head_dim * num_heads == self.embed_dim
106
+ ), "embed_dim must be divisible by num_heads"
107
+
108
+ if add_bias_kv:
109
+ self.bias_k = Parameter(
110
+ torch.empty((1, 1, embed_dim), **factory_kwargs))
111
+ self.bias_v = Parameter(
112
+ torch.empty((1, 1, embed_dim), **factory_kwargs))
113
+ else:
114
+ self.bias_k = self.bias_v = None
115
+
116
+ if linear1_cls == Linear:
117
+ if not self._qkv_same_embed_dim:
118
+ self.q_proj_weight = Parameter(
119
+ torch.empty((embed_dim, embed_dim), **factory_kwargs))
120
+ self.k_proj_weight = Parameter(
121
+ torch.empty((embed_dim, self.kdim), **factory_kwargs))
122
+ self.v_proj_weight = Parameter(
123
+ torch.empty((embed_dim, self.vdim), **factory_kwargs))
124
+ self.register_parameter("in_proj_weight", None)
125
+ else:
126
+ self.in_proj_weight = Parameter(
127
+ torch.empty((3 * embed_dim, embed_dim), **factory_kwargs))
128
+ self.register_parameter("q_proj_weight", None)
129
+ self.register_parameter("k_proj_weight", None)
130
+ self.register_parameter("v_proj_weight", None)
131
+
132
+ if bias:
133
+ self.in_proj_bias = Parameter(
134
+ torch.empty(3 * embed_dim, **factory_kwargs))
135
+ else:
136
+ self.register_parameter("in_proj_bias", None)
137
+ self.out_proj = NonDynamicallyQuantizableLinear(
138
+ embed_dim, embed_dim, bias=bias, **factory_kwargs)
139
+
140
+ self._reset_parameters()
141
+ else:
142
+ if not self._qkv_same_embed_dim:
143
+ raise NotImplementedError
144
+ else:
145
+ self.in_proj_linear = linear1_cls(
146
+ embed_dim, 3 * embed_dim, bias=bias, **factory_kwargs)
147
+ self.in_proj_weight = self.in_proj_linear.weight
148
+
149
+ self.register_parameter("q_proj_weight", None)
150
+ self.register_parameter("k_proj_weight", None)
151
+ self.register_parameter("v_proj_weight", None)
152
+
153
+ if bias:
154
+ self.in_proj_bias = self.in_proj_linear.bias
155
+ else:
156
+ self.register_parameter("in_proj_bias", None)
157
+
158
+ self.out_proj = linear2_cls(
159
+ embed_dim, embed_dim, bias=bias, **factory_kwargs)
160
+
161
+ if self.bias_k is not None:
162
+ xavier_normal_(self.bias_k)
163
+ if self.bias_v is not None:
164
+ xavier_normal_(self.bias_v)
165
+
166
+ self.add_zero_attn = add_zero_attn
167
+
168
+ def _reset_parameters(self):
169
+ if self._qkv_same_embed_dim:
170
+ xavier_uniform_(self.in_proj_weight)
171
+ else:
172
+ xavier_uniform_(self.q_proj_weight)
173
+ xavier_uniform_(self.k_proj_weight)
174
+ xavier_uniform_(self.v_proj_weight)
175
+
176
+ if self.in_proj_bias is not None:
177
+ constant_(self.in_proj_bias, 0.0)
178
+ constant_(self.out_proj.bias, 0.0)
179
+
180
+ if self.bias_k is not None:
181
+ xavier_normal_(self.bias_k)
182
+ if self.bias_v is not None:
183
+ xavier_normal_(self.bias_v)
184
+
185
+ def __setstate__(self, state):
186
+ # Support loading old MultiheadAttention checkpoints generated by v1.1.0
187
+ if "_qkv_same_embed_dim" not in state:
188
+ state["_qkv_same_embed_dim"] = True
189
+
190
+ super(MultiheadAttention, self).__setstate__(state)
191
+
192
+ def forward(
193
+ self,
194
+ query: Tensor,
195
+ key: Tensor,
196
+ value: Tensor,
197
+ key_padding_mask: Optional[Tensor]=None,
198
+ need_weights: bool=True,
199
+ attn_mask: Optional[Tensor]=None,
200
+ average_attn_weights: bool=True,cache=None
201
+ ) -> Tuple[Tensor, Optional[Tensor]]:
202
+ r"""
203
+ Args:
204
+ query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
205
+ or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
206
+ :math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
207
+ Queries are compared against key-value pairs to produce the output.
208
+ See "Attention Is All You Need" for more details.
209
+ key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
210
+ or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
211
+ :math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
212
+ See "Attention Is All You Need" for more details.
213
+ value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
214
+ ``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
215
+ sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
216
+ See "Attention Is All You Need" for more details.
217
+ key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
218
+ to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
219
+ Binary and byte masks are supported.
220
+ For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
221
+ the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
222
+ need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
223
+ Default: ``True``.
224
+ attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
225
+ :math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
226
+ :math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
227
+ broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
228
+ Binary, byte, and float masks are supported. For a binary mask, a ``True`` value indicates that the
229
+ corresponding position is not allowed to attend. For a byte mask, a non-zero value indicates that the
230
+ corresponding position is not allowed to attend. For a float mask, the mask values will be added to
231
+ the attention weight.
232
+ average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
233
+ heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
234
+ effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
235
+
236
+ Outputs:
237
+ - **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
238
+ :math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
239
+ where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
240
+ embedding dimension ``embed_dim``.
241
+ - **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
242
+ returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
243
+ :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
244
+ :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
245
+ head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
246
+
247
+ .. note::
248
+ `batch_first` argument is ignored for unbatched inputs.
249
+ """
250
+ is_batched = query.dim() == 3
251
+ if key_padding_mask is not None:
252
+ _kpm_dtype = key_padding_mask.dtype
253
+ if _kpm_dtype != torch.bool and not torch.is_floating_point(
254
+ key_padding_mask):
255
+ raise AssertionError(
256
+ "only bool and floating types of key_padding_mask are supported"
257
+ )
258
+ why_not_fast_path = ""
259
+ if not is_batched:
260
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
261
+ elif query is not key or key is not value:
262
+ # When lifting this restriction, don't forget to either
263
+ # enforce that the dtypes all match or test cases where
264
+ # they don't!
265
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
266
+ elif (self.in_proj_bias is not None and
267
+ query.dtype != self.in_proj_bias.dtype):
268
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
269
+ elif (self.in_proj_weight is not None and
270
+ query.dtype != self.in_proj_weight.dtype):
271
+ # this case will fail anyway, but at least they'll get a useful error message.
272
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
273
+ elif self.training:
274
+ why_not_fast_path = "training is enabled"
275
+ elif not self.batch_first:
276
+ why_not_fast_path = "batch_first was not True"
277
+ elif self.bias_k is not None:
278
+ why_not_fast_path = "self.bias_k was not None"
279
+ elif self.bias_v is not None:
280
+ why_not_fast_path = "self.bias_v was not None"
281
+ elif self.dropout:
282
+ why_not_fast_path = f"dropout was {self.dropout}, required zero"
283
+ elif self.add_zero_attn:
284
+ why_not_fast_path = "add_zero_attn was enabled"
285
+ elif not self._qkv_same_embed_dim:
286
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
287
+ elif attn_mask is not None:
288
+ why_not_fast_path = "attn_mask was not None"
289
+ elif query.is_nested and key_padding_mask is not None:
290
+ why_not_fast_path = (
291
+ "key_padding_mask is not supported with NestedTensor input")
292
+ elif self.num_heads % 2 == 1:
293
+ why_not_fast_path = "num_heads is odd"
294
+ elif torch.is_autocast_enabled():
295
+ why_not_fast_path = "autocast is enabled"
296
+
297
+ if not why_not_fast_path:
298
+ tensor_args = (query, key, value, self.in_proj_weight,
299
+ self.in_proj_bias, self.out_proj.weight,
300
+ self.out_proj.bias, )
301
+ # We have to use list comprehensions below because TorchScript does not support
302
+ # generator expressions.
303
+ if torch.overrides.has_torch_function(tensor_args):
304
+ why_not_fast_path = "some Tensor argument has_torch_function"
305
+ elif not all([(x is None or x.is_cuda or "cpu" in str(x.device))
306
+ for x in tensor_args]):
307
+ why_not_fast_path = (
308
+ "some Tensor argument is neither CUDA nor CPU")
309
+ elif torch.is_grad_enabled() and any(
310
+ [x is not None and x.requires_grad for x in tensor_args]):
311
+ why_not_fast_path = (
312
+ "grad is enabled and at least one of query or the "
313
+ "input/output projection weights or biases requires_grad")
314
+ if not why_not_fast_path:
315
+ return torch._native_multi_head_attention(
316
+ query,
317
+ key,
318
+ value,
319
+ self.embed_dim,
320
+ self.num_heads,
321
+ self.in_proj_weight,
322
+ self.in_proj_bias,
323
+ self.out_proj.weight,
324
+ self.out_proj.bias,
325
+ key_padding_mask
326
+ if key_padding_mask is not None else attn_mask,
327
+ need_weights,
328
+ average_attn_weights,
329
+ 1 if key_padding_mask is not None else 0
330
+ if attn_mask is not None else None, )
331
+
332
+ any_nested = query.is_nested or key.is_nested or value.is_nested
333
+ assert not any_nested, (
334
+ "MultiheadAttention does not support NestedTensor outside of its fast path. "
335
+ + f"The fast path was not hit because {why_not_fast_path}")
336
+
337
+ if self.batch_first and is_batched:
338
+ # make sure that the transpose op does not affect the "is" property
339
+ if key is value:
340
+ if query is key:
341
+ query = key = value = query.transpose(1, 0)
342
+ else:
343
+ query, key = [x.transpose(1, 0) for x in (query, key)]
344
+ value = key
345
+ else:
346
+ query, key, value = [
347
+ x.transpose(1, 0) for x in (query, key, value)
348
+ ]
349
+
350
+ if not self._qkv_same_embed_dim:
351
+ attn_output, attn_output_weights = F.multi_head_attention_forward(
352
+ query,
353
+ key,
354
+ value,
355
+ self.embed_dim,
356
+ self.num_heads,
357
+ self.in_proj_weight,
358
+ self.in_proj_bias,
359
+ self.bias_k,
360
+ self.bias_v,
361
+ self.add_zero_attn,
362
+ self.dropout,
363
+ self.out_proj.weight,
364
+ self.out_proj.bias,
365
+ training=self.training,
366
+ key_padding_mask=key_padding_mask,
367
+ need_weights=need_weights,
368
+ attn_mask=attn_mask,
369
+ use_separate_proj_weight=True,
370
+ q_proj_weight=self.q_proj_weight,
371
+ k_proj_weight=self.k_proj_weight,
372
+ v_proj_weight=self.v_proj_weight,
373
+ average_attn_weights=average_attn_weights,cache=cache )
374
+ else:
375
+ attn_output, attn_output_weights = F.multi_head_attention_forward(
376
+ query,
377
+ key,
378
+ value,
379
+ self.embed_dim,
380
+ self.num_heads,
381
+ self.in_proj_weight,
382
+ self.in_proj_bias,
383
+ self.bias_k,
384
+ self.bias_v,
385
+ self.add_zero_attn,
386
+ self.dropout,
387
+ self.out_proj.weight,
388
+ self.out_proj.bias,
389
+ training=self.training,
390
+ key_padding_mask=key_padding_mask,
391
+ need_weights=need_weights,
392
+ attn_mask=attn_mask,
393
+ average_attn_weights=average_attn_weights,cache=cache )
394
+ if self.batch_first and is_batched:
395
+ return attn_output.transpose(1, 0), attn_output_weights
396
+ else:
397
+ return attn_output, attn_output_weights
AR/modules/embedding.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/embedding.py
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class TokenEmbedding(nn.Module):
9
+ def __init__(
10
+ self,
11
+ embedding_dim: int,
12
+ vocab_size: int,
13
+ dropout: float=0.0, ):
14
+ super().__init__()
15
+
16
+ self.vocab_size = vocab_size
17
+ self.embedding_dim = embedding_dim
18
+
19
+ self.dropout = torch.nn.Dropout(p=dropout)
20
+ self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
21
+
22
+ @property
23
+ def weight(self) -> torch.Tensor:
24
+ return self.word_embeddings.weight
25
+
26
+ def embedding(self, index: int) -> torch.Tensor:
27
+ return self.word_embeddings.weight[index:index + 1]
28
+
29
+ def forward(self, x: torch.Tensor):
30
+ x = self.word_embeddings(x)
31
+ x = self.dropout(x)
32
+ return x
33
+
34
+
35
+ class SinePositionalEmbedding(nn.Module):
36
+ def __init__(
37
+ self,
38
+ embedding_dim: int,
39
+ dropout: float=0.0,
40
+ scale: bool=False,
41
+ alpha: bool=False, ):
42
+ super().__init__()
43
+ self.embedding_dim = embedding_dim
44
+ self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
45
+ self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
46
+ self.dropout = torch.nn.Dropout(p=dropout)
47
+
48
+ self.reverse = False
49
+ self.pe = None
50
+ self.extend_pe(torch.tensor(0.0).expand(1, 4000))
51
+
52
+ def extend_pe(self, x):
53
+ """Reset the positional encodings."""
54
+ if self.pe is not None:
55
+ if self.pe.size(1) >= x.size(1):
56
+ if self.pe.dtype != x.dtype or self.pe.device != x.device:
57
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
58
+ return
59
+ pe = torch.zeros(x.size(1), self.embedding_dim)
60
+ if self.reverse:
61
+ position = torch.arange(
62
+ x.size(1) - 1, -1, -1.0, dtype=torch.float32).unsqueeze(1)
63
+ else:
64
+ position = torch.arange(
65
+ 0, x.size(1), dtype=torch.float32).unsqueeze(1)
66
+ div_term = torch.exp(
67
+ torch.arange(0, self.embedding_dim, 2, dtype=torch.float32) *
68
+ -(math.log(10000.0) / self.embedding_dim))
69
+ pe[:, 0::2] = torch.sin(position * div_term)
70
+ pe[:, 1::2] = torch.cos(position * div_term)
71
+ pe = pe.unsqueeze(0)
72
+ self.pe = pe.to(device=x.device, dtype=x.dtype).detach()
73
+
74
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
75
+ self.extend_pe(x)
76
+ output = x.unsqueeze(-1) if x.ndim == 2 else x
77
+ output = output * self.x_scale + self.alpha * self.pe[:, :x.size(1)]
78
+ return self.dropout(output)
AR/modules/lr_schedulers.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/model/lr_schedulers.py
2
+ import math
3
+
4
+ import torch
5
+ from matplotlib import pyplot as plt
6
+ from torch import nn
7
+ from torch.optim import Adam
8
+
9
+
10
+ class WarmupCosineLRSchedule(torch.optim.lr_scheduler._LRScheduler):
11
+ """
12
+ Implements Warmup learning rate schedule until 'warmup_steps', going from 'init_lr' to 'peak_lr' for multiple optimizers.
13
+ """
14
+
15
+ def __init__(self,
16
+ optimizer,
17
+ init_lr,
18
+ peak_lr,
19
+ end_lr,
20
+ warmup_steps=10000,
21
+ total_steps=400000,
22
+ current_step=0):
23
+ self.init_lr = init_lr
24
+ self.peak_lr = peak_lr
25
+ self.end_lr = end_lr
26
+ self.optimizer = optimizer
27
+ self._warmup_rate = (peak_lr - init_lr) / warmup_steps
28
+ self._decay_rate = (end_lr - peak_lr) / (total_steps - warmup_steps)
29
+ self._current_step = current_step
30
+ self.lr = init_lr
31
+ self.warmup_steps = warmup_steps
32
+ self.total_steps = total_steps
33
+ self._last_lr = [self.lr]
34
+
35
+ def set_lr(self, lr):
36
+ self._last_lr = [g['lr'] for g in self.optimizer.param_groups]
37
+ for g in self.optimizer.param_groups:
38
+ # g['lr'] = lr
39
+ g['lr'] = self.end_lr###锁定用线性
40
+
41
+ def step(self):
42
+ if self._current_step < self.warmup_steps:
43
+ lr = self.init_lr + self._warmup_rate * self._current_step
44
+
45
+ elif self._current_step > self.total_steps:
46
+ lr = self.end_lr
47
+
48
+ else:
49
+ decay_ratio = (self._current_step - self.warmup_steps) / (
50
+ self.total_steps - self.warmup_steps)
51
+ if decay_ratio < 0.0 or decay_ratio > 1.0:
52
+ raise RuntimeError(
53
+ "Decay ratio must be in [0.0, 1.0]. Fix LR scheduler settings."
54
+ )
55
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
56
+ lr = self.end_lr + coeff * (self.peak_lr - self.end_lr)
57
+
58
+ self.lr=lr=self.end_lr=0.002###锁定用线性###不听话,直接锁定!
59
+ self.set_lr(lr)
60
+ self.lr = lr
61
+ self._current_step += 1
62
+ return self.lr
63
+
64
+
65
+
66
+ if __name__ == '__main__':
67
+ m = nn.Linear(10, 10)
68
+ opt = Adam(m.parameters(), lr=1e-4)
69
+ s = WarmupCosineLRSchedule(
70
+ opt,
71
+ 1e-6,
72
+ 2e-4,
73
+ 1e-6,
74
+ warmup_steps=2000,
75
+ total_steps=20000,
76
+ current_step=0)
77
+ lrs = []
78
+ for i in range(25000):
79
+ s.step()
80
+ lrs.append(s.lr)
81
+ print(s.lr)
82
+
83
+ plt.plot(lrs)
84
+ plt.plot(range(0, 25000), lrs)
85
+ plt.show()
AR/modules/optim.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
2
+ #
3
+ # See ../LICENSE for clarification regarding multiple authors
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import contextlib
17
+ import logging
18
+ from collections import defaultdict
19
+ from typing import List
20
+ from typing import Tuple
21
+
22
+ import torch
23
+ from torch import Tensor
24
+ from torch.optim import Optimizer
25
+
26
+
27
+ class BatchedOptimizer(Optimizer):
28
+ """
29
+ This class adds to class Optimizer the capability to optimize parameters in batches:
30
+ it will stack the parameters and their grads for you so the optimizer can work
31
+ on tensors with an extra leading dimension. This is intended for speed with GPUs,
32
+ as it reduces the number of kernels launched in the optimizer.
33
+
34
+ Args:
35
+ params:
36
+ """
37
+
38
+ def __init__(self, params, defaults):
39
+ super(BatchedOptimizer, self).__init__(params, defaults)
40
+
41
+ @contextlib.contextmanager
42
+ def batched_params(self, param_group, group_params_names):
43
+ """
44
+ This function returns (technically, yields) a list of
45
+ of tuples (p, state), where
46
+ p is a `fake` parameter that is stacked (over axis 0) from real parameters
47
+ that share the same shape, and its gradient is also stacked;
48
+ `state` is the state corresponding to this batch of parameters
49
+ (it will be physically located in the "state" for one of the real
50
+ parameters, the last one that has any particular shape and dtype).
51
+
52
+ This function is decorated as a context manager so that it can
53
+ write parameters back to their "real" locations.
54
+
55
+ The idea is, instead of doing:
56
+ <code>
57
+ for p in group["params"]:
58
+ state = self.state[p]
59
+ ...
60
+ </code>
61
+ you can do:
62
+ <code>
63
+ with self.batched_params(group["params"]) as batches:
64
+ for p, state, p_names in batches:
65
+ ...
66
+ </code>
67
+
68
+ Args:
69
+ group: a parameter group, which is a list of parameters; should be
70
+ one of self.param_groups.
71
+ group_params_names: name for each parameter in group,
72
+ which is List[str].
73
+ """
74
+ batches = defaultdict(
75
+ list
76
+ ) # `batches` maps from tuple (dtype_as_str,*shape) to list of nn.Parameter
77
+ batches_names = defaultdict(
78
+ list
79
+ ) # `batches` maps from tuple (dtype_as_str,*shape) to list of str
80
+
81
+ assert len(param_group) == len(group_params_names)
82
+ for p, named_p in zip(param_group, group_params_names):
83
+ key = (str(p.dtype), *p.shape)
84
+ batches[key].append(p)
85
+ batches_names[key].append(named_p)
86
+
87
+ batches_names_keys = list(batches_names.keys())
88
+ sorted_idx = sorted(
89
+ range(len(batches_names)), key=lambda i: batches_names_keys[i])
90
+ batches_names = [
91
+ batches_names[batches_names_keys[idx]] for idx in sorted_idx
92
+ ]
93
+ batches = [batches[batches_names_keys[idx]] for idx in sorted_idx]
94
+
95
+ stacked_params_dict = dict()
96
+
97
+ # turn batches into a list, in deterministic order.
98
+ # tuples will contain tuples of (stacked_param, state, stacked_params_names),
99
+ # one for each batch in `batches`.
100
+ tuples = []
101
+
102
+ for batch, batch_names in zip(batches, batches_names):
103
+ p = batch[0]
104
+ # we arbitrarily store the state in the
105
+ # state corresponding to the 1st parameter in the
106
+ # group. class Optimizer will take care of saving/loading state.
107
+ state = self.state[p]
108
+ p_stacked = torch.stack(batch)
109
+ grad = torch.stack([
110
+ torch.zeros_like(p) if p.grad is None else p.grad for p in batch
111
+ ])
112
+ p_stacked.grad = grad
113
+ stacked_params_dict[key] = p_stacked
114
+ tuples.append((p_stacked, state, batch_names))
115
+
116
+ yield tuples # <-- calling code will do the actual optimization here!
117
+
118
+ for ((stacked_params, _state, _names), batch) in zip(tuples, batches):
119
+ for i, p in enumerate(batch): # batch is list of Parameter
120
+ p.copy_(stacked_params[i])
121
+
122
+
123
+ class ScaledAdam(BatchedOptimizer):
124
+ """
125
+ Implements 'Scaled Adam', a variant of Adam where we scale each parameter's update
126
+ proportional to the norm of that parameter; and also learn the scale of the parameter,
127
+ in log space, subject to upper and lower limits (as if we had factored each parameter as
128
+ param = underlying_param * log_scale.exp())
129
+
130
+
131
+ Args:
132
+ params: The parameters or param_groups to optimize (like other Optimizer subclasses)
133
+ lr: The learning rate. We will typically use a learning rate schedule that starts
134
+ at 0.03 and decreases over time, i.e. much higher than other common
135
+ optimizers.
136
+ clipping_scale: (e.g. 2.0)
137
+ A scale for gradient-clipping: if specified, the normalized gradients
138
+ over the whole model will be clipped to have 2-norm equal to
139
+ `clipping_scale` times the median 2-norm over the most recent period
140
+ of `clipping_update_period` minibatches. By "normalized gradients",
141
+ we mean after multiplying by the rms parameter value for this tensor
142
+ [for non-scalars]; this is appropriate because our update is scaled
143
+ by this quantity.
144
+ betas: beta1,beta2 are momentum constants for regular momentum, and moving sum-sq grad.
145
+ Must satisfy 0 < beta <= beta2 < 1.
146
+ scalar_lr_scale: A scaling factor on the learning rate, that we use to update the
147
+ scale of each parameter tensor and scalar parameters of the mode..
148
+ If each parameter were decomposed
149
+ as p * p_scale.exp(), where (p**2).mean().sqrt() == 1.0, scalar_lr_scale
150
+ would be a the scaling factor on the learning rate of p_scale.
151
+ eps: A general-purpose epsilon to prevent division by zero
152
+ param_min_rms: Minimum root-mean-square value of parameter tensor, for purposes of
153
+ learning the scale on the parameters (we'll constrain the rms of each non-scalar
154
+ parameter tensor to be >= this value)
155
+ param_max_rms: Maximum root-mean-square value of parameter tensor, for purposes of
156
+ learning the scale on the parameters (we'll constrain the rms of each non-scalar
157
+ parameter tensor to be <= this value)
158
+ scalar_max: Maximum absolute value for scalar parameters (applicable if your
159
+ model has any parameters with numel() == 1).
160
+ size_update_period: The periodicity, in steps, with which we update the size (scale)
161
+ of the parameter tensor. This is provided to save a little time
162
+ in the update.
163
+ clipping_update_period: if clipping_scale is specified, this is the period
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ params,
169
+ lr=3e-02,
170
+ clipping_scale=None,
171
+ betas=(0.9, 0.98),
172
+ scalar_lr_scale=0.1,
173
+ eps=1.0e-08,
174
+ param_min_rms=1.0e-05,
175
+ param_max_rms=3.0,
176
+ scalar_max=10.0,
177
+ size_update_period=4,
178
+ clipping_update_period=100,
179
+ parameters_names=None,
180
+ show_dominant_parameters=True, ):
181
+
182
+ assert parameters_names is not None, (
183
+ "Please prepare parameters_names,"
184
+ "which is a List[List[str]]. Each List[str] is for a group"
185
+ "and each str is for a parameter")
186
+ defaults = dict(
187
+ lr=lr,
188
+ clipping_scale=clipping_scale,
189
+ betas=betas,
190
+ scalar_lr_scale=scalar_lr_scale,
191
+ eps=eps,
192
+ param_min_rms=param_min_rms,
193
+ param_max_rms=param_max_rms,
194
+ scalar_max=scalar_max,
195
+ size_update_period=size_update_period,
196
+ clipping_update_period=clipping_update_period, )
197
+
198
+ super(ScaledAdam, self).__init__(params, defaults)
199
+ assert len(self.param_groups) == len(parameters_names)
200
+ self.parameters_names = parameters_names
201
+ self.show_dominant_parameters = show_dominant_parameters
202
+
203
+ def __setstate__(self, state):
204
+ super(ScaledAdam, self).__setstate__(state)
205
+
206
+ @torch.no_grad()
207
+ def step(self, closure=None):
208
+ """Performs a single optimization step.
209
+
210
+ Arguments:
211
+ closure (callable, optional): A closure that reevaluates the model
212
+ and returns the loss.
213
+ """
214
+ loss = None
215
+ if closure is not None:
216
+ with torch.enable_grad():
217
+ loss = closure()
218
+
219
+ batch = True
220
+
221
+ for group, group_params_names in zip(self.param_groups,
222
+ self.parameters_names):
223
+
224
+ with self.batched_params(group["params"],
225
+ group_params_names) as batches:
226
+
227
+ # batches is list of pairs (stacked_param, state). stacked_param is like
228
+ # a regular parameter, and will have a .grad, but the 1st dim corresponds to
229
+ # a stacking dim, it is not a real dim.
230
+
231
+ if (len(batches[0][1]) ==
232
+ 0): # if len(first state) == 0: not yet initialized
233
+ clipping_scale = 1
234
+ else:
235
+ clipping_scale = self._get_clipping_scale(group, batches)
236
+
237
+ for p, state, _ in batches:
238
+ # Perform optimization step.
239
+ # grad is not going to be None, we handled that when creating the batches.
240
+ grad = p.grad
241
+ if grad.is_sparse:
242
+ raise RuntimeError(
243
+ "ScaledAdam optimizer does not support sparse gradients"
244
+ )
245
+ # State initialization
246
+ if len(state) == 0:
247
+ self._init_state(group, p, state)
248
+
249
+ self._step_one_batch(group, p, state, clipping_scale)
250
+
251
+ return loss
252
+
253
+ def _init_state(self, group: dict, p: Tensor, state: dict):
254
+ """
255
+ Initializes state dict for parameter 'p'. Assumes that dim 0 of tensor p
256
+ is actually the batch dimension, corresponding to batched-together
257
+ parameters of a given shape.
258
+
259
+
260
+ Args:
261
+ group: Dict to look up configuration values.
262
+ p: The parameter that we are initializing the state for
263
+ state: Dict from string to whatever state we are initializing
264
+ """
265
+ size_update_period = group["size_update_period"]
266
+
267
+ state["step"] = 0
268
+
269
+ kwargs = {"device": p.device, "dtype": p.dtype}
270
+
271
+ # 'delta' implements conventional momentum. There are
272
+ # several different kinds of update going on, so rather than
273
+ # compute "exp_avg" like in Adam, we store and decay a
274
+ # parameter-change "delta", which combines all forms of
275
+ # update. this is equivalent to how it's done in Adam,
276
+ # except for the first few steps.
277
+ state["delta"] = torch.zeros_like(
278
+ p, memory_format=torch.preserve_format)
279
+
280
+ batch_size = p.shape[0]
281
+ numel = p.numel() // batch_size
282
+ numel = p.numel()
283
+
284
+ if numel > 1:
285
+ # "param_rms" just periodically records the scalar root-mean-square value of
286
+ # the parameter tensor.
287
+ # it has a shape like (batch_size, 1, 1, 1, 1)
288
+ param_rms = (
289
+ (p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt())
290
+ state["param_rms"] = param_rms
291
+
292
+ state["scale_exp_avg_sq"] = torch.zeros_like(param_rms)
293
+ state["scale_grads"] = torch.zeros(size_update_period,
294
+ *param_rms.shape, **kwargs)
295
+
296
+ # exp_avg_sq is the weighted sum of scaled gradients. as in Adam.
297
+ state["exp_avg_sq"] = torch.zeros_like(
298
+ p, memory_format=torch.preserve_format)
299
+
300
+ def _get_clipping_scale(self,
301
+ group: dict,
302
+ tuples: List[Tuple[Tensor, dict, List[str]]]
303
+ ) -> float:
304
+ """
305
+ Returns a scalar factor <= 1.0 that dictates gradient clipping, i.e. we will scale the gradients
306
+ by this amount before applying the rest of the update.
307
+
308
+ Args:
309
+ group: the parameter group, an item in self.param_groups
310
+ tuples: a list of tuples of (param, state, param_names)
311
+ where param is a batched set of parameters,
312
+ with a .grad (1st dim is batch dim)
313
+ and state is the state-dict where optimization parameters are kept.
314
+ param_names is a List[str] while each str is name for a parameter
315
+ in batched set of parameters "param".
316
+ """
317
+ assert len(tuples) >= 1
318
+ clipping_scale = group["clipping_scale"]
319
+ (first_p, first_state, _) = tuples[0]
320
+ step = first_state["step"]
321
+ if clipping_scale is None or step == 0:
322
+ # no clipping. return early on step == 0 because the other
323
+ # parameters' state won't have been initialized yet.
324
+ return 1.0
325
+ clipping_update_period = group["clipping_update_period"]
326
+
327
+ tot_sumsq = torch.tensor(0.0, device=first_p.device)
328
+ for (p, state, param_names) in tuples:
329
+ grad = p.grad
330
+ if grad.is_sparse:
331
+ raise RuntimeError(
332
+ "ScaledAdam optimizer does not support sparse gradients")
333
+ if p.numel() == p.shape[0]: # a batch of scalars
334
+ tot_sumsq += (grad**2).sum() # sum() to change shape [1] to []
335
+ else:
336
+ tot_sumsq += ((grad * state["param_rms"])**2).sum()
337
+
338
+ tot_norm = tot_sumsq.sqrt()
339
+ if "model_norms" not in first_state:
340
+ first_state["model_norms"] = torch.zeros(
341
+ clipping_update_period, device=p.device)
342
+ first_state["model_norms"][step % clipping_update_period] = tot_norm
343
+
344
+ if step % clipping_update_period == 0:
345
+ # Print some stats.
346
+ # We don't reach here if step == 0 because we would have returned
347
+ # above.
348
+ sorted_norms = first_state["model_norms"].sort()[0].to("cpu")
349
+ quartiles = []
350
+ for n in range(0, 5):
351
+ index = min(
352
+ clipping_update_period - 1,
353
+ (clipping_update_period // 4) * n, )
354
+ quartiles.append(sorted_norms[index].item())
355
+
356
+ median = quartiles[2]
357
+ threshold = clipping_scale * median
358
+ first_state["model_norm_threshold"] = threshold
359
+ percent_clipped = (first_state["num_clipped"] * 100.0 /
360
+ clipping_update_period
361
+ if "num_clipped" in first_state else 0.0)
362
+ first_state["num_clipped"] = 0
363
+ quartiles = " ".join(["%.3e" % x for x in quartiles])
364
+ logging.info(
365
+ f"Clipping_scale={clipping_scale}, grad-norm quartiles {quartiles}, "
366
+ f"threshold={threshold:.3e}, percent-clipped={percent_clipped:.1f}"
367
+ )
368
+
369
+ if step < clipping_update_period:
370
+ return 1.0 # We have not yet estimated a norm to clip to.
371
+ else:
372
+ try:
373
+ model_norm_threshold = first_state["model_norm_threshold"]
374
+ except KeyError:
375
+ logging.info(
376
+ "Warning: model_norm_threshold not in state: possibly "
377
+ "you changed config when restarting, adding clipping_scale option?"
378
+ )
379
+ return 1.0
380
+ ans = min(1.0, (model_norm_threshold / (tot_norm + 1.0e-20)).item())
381
+ if ans < 1.0:
382
+ first_state["num_clipped"] += 1
383
+ if ans < 0.1:
384
+ logging.warn(
385
+ f"Scaling gradients by {ans}, model_norm_threshold={model_norm_threshold}"
386
+ )
387
+ if self.show_dominant_parameters:
388
+ assert p.shape[0] == len(param_names)
389
+ self._show_gradient_dominating_parameter(tuples, tot_sumsq)
390
+ return ans
391
+
392
+ def _show_gradient_dominating_parameter(
393
+ self, tuples: List[Tuple[Tensor, dict, List[str]]],
394
+ tot_sumsq: Tensor):
395
+ """
396
+ Show information of parameter wihch dominanting tot_sumsq.
397
+
398
+ Args:
399
+ tuples: a list of tuples of (param, state, param_names)
400
+ where param is a batched set of parameters,
401
+ with a .grad (1st dim is batch dim)
402
+ and state is the state-dict where optimization parameters are kept.
403
+ param_names is a List[str] while each str is name for a parameter
404
+ in batched set of parameters "param".
405
+ tot_sumsq: sumsq of all parameters. Though it's could be calculated
406
+ from tuples, we still pass it to save some time.
407
+ """
408
+ all_sumsq_orig = {}
409
+ for (p, state, batch_param_names) in tuples:
410
+ # p is a stacked batch parameters.
411
+ batch_grad = p.grad
412
+ if p.numel() == p.shape[0]: # a batch of scalars
413
+ batch_sumsq_orig = batch_grad**2
414
+ # Dummpy values used by following `zip` statement.
415
+ batch_rms_orig = torch.ones(p.shape[0])
416
+ else:
417
+ batch_rms_orig = state["param_rms"]
418
+ batch_sumsq_orig = ((batch_grad * batch_rms_orig)**2).sum(
419
+ dim=list(range(1, batch_grad.ndim)))
420
+
421
+ for name, sumsq_orig, rms, grad in zip(batch_param_names,
422
+ batch_sumsq_orig,
423
+ batch_rms_orig, batch_grad):
424
+
425
+ proportion_orig = sumsq_orig / tot_sumsq
426
+ all_sumsq_orig[name] = (proportion_orig, sumsq_orig, rms, grad)
427
+
428
+ assert torch.isclose(
429
+ sum([value[0] for value in all_sumsq_orig.values()]).cpu(),
430
+ torch.tensor(1.0), )
431
+ sorted_by_proportion = {
432
+ k: v
433
+ for k, v in sorted(
434
+ all_sumsq_orig.items(),
435
+ key=lambda item: item[1][0],
436
+ reverse=True, )
437
+ }
438
+ dominant_param_name = next(iter(sorted_by_proportion))
439
+ (dominant_proportion, dominant_sumsq, dominant_rms,
440
+ dominant_grad, ) = sorted_by_proportion[dominant_param_name]
441
+ logging.info(f"Parameter Dominanting tot_sumsq {dominant_param_name}"
442
+ f" with proportion {dominant_proportion:.2f},"
443
+ f" where dominant_sumsq=(grad_sumsq*orig_rms_sq)"
444
+ f"={dominant_sumsq:.3e},"
445
+ f" grad_sumsq = {(dominant_grad**2).sum():.3e},"
446
+ f" orig_rms_sq={(dominant_rms**2).item():.3e}")
447
+
448
+ def _step_one_batch(self,
449
+ group: dict,
450
+ p: Tensor,
451
+ state: dict,
452
+ clipping_scale: float):
453
+ """
454
+ Do the step for one parameter, which is actually going to be a batch of
455
+ `real` parameters, with dim 0 as the batch dim.
456
+ Args:
457
+ group: dict to look up configuration values
458
+ p: parameter to update (actually multiple parameters stacked together
459
+ as a batch)
460
+ state: state-dict for p, to look up the optimizer state
461
+ """
462
+ lr = group["lr"]
463
+ size_update_period = group["size_update_period"]
464
+ beta1 = group["betas"][0]
465
+
466
+ grad = p.grad
467
+ if clipping_scale != 1.0:
468
+ grad = grad * clipping_scale
469
+ step = state["step"]
470
+ delta = state["delta"]
471
+
472
+ delta.mul_(beta1)
473
+ batch_size = p.shape[0]
474
+ numel = p.numel() // batch_size
475
+ if numel > 1:
476
+ # Update the size/scale of p, and set param_rms
477
+ scale_grads = state["scale_grads"]
478
+ scale_grads[step % size_update_period] = (p * grad).sum(
479
+ dim=list(range(1, p.ndim)), keepdim=True)
480
+ if step % size_update_period == size_update_period - 1:
481
+ param_rms = state["param_rms"] # shape: (batch_size, 1, 1, ..)
482
+ param_rms.copy_((p**2)
483
+ .mean(dim=list(range(1, p.ndim)), keepdim=True)
484
+ .sqrt())
485
+ if step > 0:
486
+ # self._size_update() learns the overall scale on the
487
+ # parameter, by shrinking or expanding it.
488
+ self._size_update(group, scale_grads, p, state)
489
+
490
+ if numel == 1:
491
+ # For parameters with 1 element we just use regular Adam.
492
+ # Updates delta.
493
+ self._step_scalar(group, p, state)
494
+ else:
495
+ self._step(group, p, state)
496
+
497
+ state["step"] = step + 1
498
+
499
+ def _size_update(self,
500
+ group: dict,
501
+ scale_grads: Tensor,
502
+ p: Tensor,
503
+ state: dict) -> None:
504
+ """
505
+ Called only where p.numel() > 1, this updates the scale of the parameter.
506
+ If we imagine: p = underlying_param * scale.exp(), and we are doing
507
+ gradient descent on underlying param and on scale, this function does the update
508
+ on `scale`.
509
+
510
+ Args:
511
+ group: dict to look up configuration values
512
+ scale_grads: a tensor of shape (size_update_period, batch_size, 1, 1,...) containing
513
+ grads w.r.t. the scales.
514
+ p: The parameter to update
515
+ state: The state-dict of p
516
+ """
517
+
518
+ param_rms = state["param_rms"]
519
+ beta1, beta2 = group["betas"]
520
+ size_lr = group["lr"] * group["scalar_lr_scale"]
521
+ param_min_rms = group["param_min_rms"]
522
+ param_max_rms = group["param_max_rms"]
523
+ eps = group["eps"]
524
+ step = state["step"]
525
+ batch_size = p.shape[0]
526
+
527
+ size_update_period = scale_grads.shape[0]
528
+ # correct beta2 for the size update period: we will have
529
+ # faster decay at this level.
530
+ beta2_corr = beta2**size_update_period
531
+
532
+ scale_exp_avg_sq = state[
533
+ "scale_exp_avg_sq"] # shape: (batch_size, 1, 1, ..)
534
+ scale_exp_avg_sq.mul_(beta2_corr).add_(
535
+ (scale_grads**2).mean(dim=0), # mean over dim `size_update_period`
536
+ alpha=1 - beta2_corr, ) # shape is (batch_size, 1, 1, ...)
537
+
538
+ # The 1st time we reach here is when size_step == 1.
539
+ size_step = (step + 1) // size_update_period
540
+ bias_correction2 = 1 - beta2_corr**size_step
541
+ # we don't bother with bias_correction1; this will help prevent divergence
542
+ # at the start of training.
543
+
544
+ denom = scale_exp_avg_sq.sqrt() + eps
545
+
546
+ scale_step = (-size_lr * (bias_correction2**0.5) *
547
+ scale_grads.sum(dim=0) / denom)
548
+
549
+ is_too_small = param_rms < param_min_rms
550
+ is_too_large = param_rms > param_max_rms
551
+
552
+ # when the param gets too small, just don't shrink it any further.
553
+ scale_step.masked_fill_(is_too_small, 0.0)
554
+ # when it gets too large, stop it from getting any larger.
555
+ scale_step.masked_fill_(is_too_large, -size_lr * size_update_period)
556
+ delta = state["delta"]
557
+ # the factor of (1-beta1) relates to momentum.
558
+ delta.add_(p * scale_step, alpha=(1 - beta1))
559
+
560
+ def _step(self, group: dict, p: Tensor, state: dict):
561
+ """
562
+ This function does the core update of self.step(), in the case where the members of
563
+ the batch have more than 1 element.
564
+
565
+ Args:
566
+ group: A dict which will be used to look up configuration values
567
+ p: The parameter to be updated
568
+ grad: The grad of p
569
+ state: The state-dict corresponding to parameter p
570
+
571
+ This function modifies p.
572
+ """
573
+ grad = p.grad
574
+ lr = group["lr"]
575
+ beta1, beta2 = group["betas"]
576
+ eps = group["eps"]
577
+ param_min_rms = group["param_min_rms"]
578
+ step = state["step"]
579
+
580
+ exp_avg_sq = state["exp_avg_sq"]
581
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2))
582
+
583
+ this_step = state["step"] - (state["zero_step"]
584
+ if "zero_step" in state else 0)
585
+ bias_correction2 = 1 - beta2**(this_step + 1)
586
+ if bias_correction2 < 0.99:
587
+ # note: not in-place.
588
+ exp_avg_sq = exp_avg_sq * (1.0 / bias_correction2)
589
+
590
+ denom = exp_avg_sq.sqrt()
591
+ denom += eps
592
+ grad = grad / denom
593
+
594
+ alpha = -lr * (1 - beta1) * state["param_rms"].clamp(min=param_min_rms)
595
+
596
+ delta = state["delta"]
597
+ delta.add_(grad * alpha)
598
+ p.add_(delta)
599
+
600
+ def _step_scalar(self, group: dict, p: Tensor, state: dict):
601
+ """
602
+ A simplified form of the core update for scalar tensors, where we cannot get a good
603
+ estimate of the parameter rms.
604
+ """
605
+ beta1, beta2 = group["betas"]
606
+ scalar_max = group["scalar_max"]
607
+ eps = group["eps"]
608
+ lr = group["lr"] * group["scalar_lr_scale"]
609
+ grad = p.grad
610
+
611
+ exp_avg_sq = state["exp_avg_sq"] # shape: (batch_size,)
612
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
613
+
614
+ # bias_correction2 is like in Adam. Don't bother with bias_correction1;
615
+ # slower update at the start will help stability anyway.
616
+ bias_correction2 = 1 - beta2**(state["step"] + 1)
617
+ denom = (exp_avg_sq / bias_correction2).sqrt() + eps
618
+
619
+ delta = state["delta"]
620
+ delta.add_(grad / denom, alpha=-lr * (1 - beta1))
621
+ p.clamp_(min=-scalar_max, max=scalar_max)
622
+ p.add_(delta)
AR/modules/patched_mha_with_cache.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn.functional import *
2
+ from torch.nn.functional import _mha_shape_check,_canonical_mask,_none_or_dtype,_in_projection_packed
3
+ # import torch
4
+ # Tensor = torch.Tensor
5
+ # from typing import Callable, List, Optional, Tuple, Union
6
+
7
+ def multi_head_attention_forward_patched(
8
+ query: Tensor,
9
+ key: Tensor,
10
+ value: Tensor,
11
+ embed_dim_to_check: int,
12
+ num_heads: int,
13
+ in_proj_weight: Optional[Tensor],
14
+ in_proj_bias: Optional[Tensor],
15
+ bias_k: Optional[Tensor],
16
+ bias_v: Optional[Tensor],
17
+ add_zero_attn: bool,
18
+ dropout_p: float,
19
+ out_proj_weight: Tensor,
20
+ out_proj_bias: Optional[Tensor],
21
+ training: bool = True,
22
+ key_padding_mask: Optional[Tensor] = None,
23
+ need_weights: bool = True,
24
+ attn_mask: Optional[Tensor] = None,
25
+ use_separate_proj_weight: bool = False,
26
+ q_proj_weight: Optional[Tensor] = None,
27
+ k_proj_weight: Optional[Tensor] = None,
28
+ v_proj_weight: Optional[Tensor] = None,
29
+ static_k: Optional[Tensor] = None,
30
+ static_v: Optional[Tensor] = None,
31
+ average_attn_weights: bool = True,
32
+ is_causal: bool = False,cache=None
33
+ ) -> Tuple[Tensor, Optional[Tensor]]:
34
+ r"""
35
+ Args:
36
+ query, key, value: map a query and a set of key-value pairs to an output.
37
+ See "Attention Is All You Need" for more details.
38
+ embed_dim_to_check: total dimension of the model.
39
+ num_heads: parallel attention heads.
40
+ in_proj_weight, in_proj_bias: input projection weight and bias.
41
+ bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
42
+ add_zero_attn: add a new batch of zeros to the key and
43
+ value sequences at dim=1.
44
+ dropout_p: probability of an element to be zeroed.
45
+ out_proj_weight, out_proj_bias: the output projection weight and bias.
46
+ training: apply dropout if is ``True``.
47
+ key_padding_mask: if provided, specified padding elements in the key will
48
+ be ignored by the attention. This is an binary mask. When the value is True,
49
+ the corresponding value on the attention layer will be filled with -inf.
50
+ need_weights: output attn_output_weights.
51
+ Default: `True`
52
+ Note: `needs_weight` defaults to `True`, but should be set to `False`
53
+ For best performance when attention weights are not nedeeded.
54
+ *Setting needs_weights to `True`
55
+ leads to a significant performance degradation.*
56
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
57
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
58
+ is_causal: If specified, applies a causal mask as attention mask, and ignores
59
+ attn_mask for computing scaled dot product attention.
60
+ Default: ``False``.
61
+ .. warning::
62
+ is_causal is provides a hint that the attn_mask is the
63
+ causal mask.Providing incorrect hints can result in
64
+ incorrect execution, including forward and backward
65
+ compatibility.
66
+ use_separate_proj_weight: the function accept the proj. weights for query, key,
67
+ and value in different forms. If false, in_proj_weight will be used, which is
68
+ a combination of q_proj_weight, k_proj_weight, v_proj_weight.
69
+ q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
70
+ static_k, static_v: static key and value used for attention operators.
71
+ average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
72
+ Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
73
+ when ``need_weights=True.``. Default: True
74
+
75
+
76
+ Shape:
77
+ Inputs:
78
+ - query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
79
+ the embedding dimension.
80
+ - key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
81
+ the embedding dimension.
82
+ - value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
83
+ the embedding dimension.
84
+ - key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
85
+ If a FloatTensor is provided, it will be directly added to the value.
86
+ If a BoolTensor is provided, the positions with the
87
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
88
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
89
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
90
+ S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
91
+ positions. If a BoolTensor is provided, positions with ``True``
92
+ are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
93
+ is provided, it will be added to the attention weight.
94
+ - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
95
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
96
+ - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
97
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
98
+
99
+ Outputs:
100
+ - attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
101
+ E is the embedding dimension.
102
+ - attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
103
+ attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
104
+ :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
105
+ :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
106
+ head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
107
+ """
108
+ tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
109
+ if has_torch_function(tens_ops):
110
+ return handle_torch_function(
111
+ multi_head_attention_forward,
112
+ tens_ops,
113
+ query,
114
+ key,
115
+ value,
116
+ embed_dim_to_check,
117
+ num_heads,
118
+ in_proj_weight,
119
+ in_proj_bias,
120
+ bias_k,
121
+ bias_v,
122
+ add_zero_attn,
123
+ dropout_p,
124
+ out_proj_weight,
125
+ out_proj_bias,
126
+ training=training,
127
+ key_padding_mask=key_padding_mask,
128
+ need_weights=need_weights,
129
+ attn_mask=attn_mask,
130
+ is_causal=is_causal,
131
+ use_separate_proj_weight=use_separate_proj_weight,
132
+ q_proj_weight=q_proj_weight,
133
+ k_proj_weight=k_proj_weight,
134
+ v_proj_weight=v_proj_weight,
135
+ static_k=static_k,
136
+ static_v=static_v,
137
+ average_attn_weights=average_attn_weights,cache=cache
138
+ )
139
+
140
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
141
+
142
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
143
+ # is batched, run the computation and before returning squeeze the
144
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
145
+ if not is_batched:
146
+ # unsqueeze if the input is unbatched
147
+ query = query.unsqueeze(1)
148
+ key = key.unsqueeze(1)
149
+ value = value.unsqueeze(1)
150
+ if key_padding_mask is not None:
151
+ key_padding_mask = key_padding_mask.unsqueeze(0)
152
+
153
+ # set up shape vars
154
+ tgt_len, bsz, embed_dim = query.shape
155
+ src_len, _, _ = key.shape
156
+
157
+ key_padding_mask = _canonical_mask(
158
+ mask=key_padding_mask,
159
+ mask_name="key_padding_mask",
160
+ other_type=_none_or_dtype(attn_mask),
161
+ other_name="attn_mask",
162
+ target_type=query.dtype
163
+ )
164
+
165
+ if is_causal and attn_mask is None:
166
+ raise RuntimeError(
167
+ "Need attn_mask if specifying the is_causal hint. "
168
+ "You may use the Transformer module method "
169
+ "`generate_square_subsequent_mask` to create this mask."
170
+ )
171
+
172
+ if is_causal and key_padding_mask is None and not need_weights:
173
+ # when we have a kpm or need weights, we need attn_mask
174
+ # Otherwise, we use the is_causal hint go as is_causal
175
+ # indicator to SDPA.
176
+ attn_mask = None
177
+ else:
178
+ attn_mask = _canonical_mask(
179
+ mask=attn_mask,
180
+ mask_name="attn_mask",
181
+ other_type=None,
182
+ other_name="",
183
+ target_type=query.dtype,
184
+ check_other=False,
185
+ )
186
+
187
+
188
+ if key_padding_mask is not None:
189
+ # We have the attn_mask, and use that to merge kpm into it.
190
+ # Turn off use of is_causal hint, as the merged mask is no
191
+ # longer causal.
192
+ is_causal = False
193
+
194
+ assert embed_dim == embed_dim_to_check, \
195
+ f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
196
+ if isinstance(embed_dim, torch.Tensor):
197
+ # embed_dim can be a tensor when JIT tracing
198
+ head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
199
+ else:
200
+ head_dim = embed_dim // num_heads
201
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
202
+ if use_separate_proj_weight:
203
+ # allow MHA to have different embedding dimensions when separate projection weights are used
204
+ assert key.shape[:2] == value.shape[:2], \
205
+ f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
206
+ else:
207
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
208
+
209
+ #
210
+ # compute in-projection
211
+ #
212
+ if not use_separate_proj_weight:
213
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
214
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
215
+ else:
216
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
217
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
218
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
219
+ if in_proj_bias is None:
220
+ b_q = b_k = b_v = None
221
+ else:
222
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
223
+ q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
224
+ if(cache!=None):
225
+ if(cache["first_infer"]==1):
226
+ cache["k"][cache["stage"]]=k
227
+ # print(0,cache["k"].shape)
228
+ cache["v"][cache["stage"]]=v
229
+ else:###12个layer每个都要留自己的cache_kv
230
+ # print(1,cache["k"].shape)
231
+ cache["k"][cache["stage"]]=torch.cat([cache["k"][cache["stage"]],k],0)##本来时序是1,但是proj的时候可能transpose了所以时序到0维了
232
+ cache["v"][cache["stage"]]=torch.cat([cache["v"][cache["stage"]],v],0)
233
+ # print(2, cache["k"].shape)
234
+ src_len = cache["k"][cache["stage"]].shape[0]
235
+ k=cache["k"][cache["stage"]]
236
+ v=cache["v"][cache["stage"]]
237
+ # if attn_mask is not None:
238
+ # attn_mask=attn_mask[-1:,]
239
+ # print(attn_mask.shape,attn_mask)
240
+ cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
241
+ # print(2333,cache)
242
+ # prep attention mask
243
+
244
+ attn_mask = _canonical_mask(
245
+ mask=attn_mask,
246
+ mask_name="attn_mask",
247
+ other_type=None,
248
+ other_name="",
249
+ target_type=q.dtype,
250
+ check_other=False,
251
+ )
252
+
253
+ if attn_mask is not None:
254
+ # ensure attn_mask's dim is 3
255
+ if attn_mask.dim() == 2:
256
+ correct_2d_size = (tgt_len, src_len)
257
+ if attn_mask.shape != correct_2d_size:
258
+ raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
259
+ attn_mask = attn_mask.unsqueeze(0)
260
+ elif attn_mask.dim() == 3:
261
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
262
+ if attn_mask.shape != correct_3d_size:
263
+ raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
264
+ else:
265
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
266
+
267
+ # add bias along batch dimension (currently second)
268
+ if bias_k is not None and bias_v is not None:
269
+ assert static_k is None, "bias cannot be added to static key."
270
+ assert static_v is None, "bias cannot be added to static value."
271
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
272
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
273
+ if attn_mask is not None:
274
+ attn_mask = pad(attn_mask, (0, 1))
275
+ if key_padding_mask is not None:
276
+ key_padding_mask = pad(key_padding_mask, (0, 1))
277
+ else:
278
+ assert bias_k is None
279
+ assert bias_v is None
280
+
281
+ #
282
+ # reshape q, k, v for multihead attention and make em batch first
283
+ #
284
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
285
+ if static_k is None:
286
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
287
+ else:
288
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
289
+ assert static_k.size(0) == bsz * num_heads, \
290
+ f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
291
+ assert static_k.size(2) == head_dim, \
292
+ f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
293
+ k = static_k
294
+ if static_v is None:
295
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
296
+ else:
297
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
298
+ assert static_v.size(0) == bsz * num_heads, \
299
+ f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
300
+ assert static_v.size(2) == head_dim, \
301
+ f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
302
+ v = static_v
303
+
304
+ # add zero attention along batch dimension (now first)
305
+ if add_zero_attn:
306
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
307
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
308
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
309
+ if attn_mask is not None:
310
+ attn_mask = pad(attn_mask, (0, 1))
311
+ if key_padding_mask is not None:
312
+ key_padding_mask = pad(key_padding_mask, (0, 1))
313
+
314
+ # update source sequence length after adjustments
315
+ src_len = k.size(1)
316
+
317
+ # merge key padding and attention masks
318
+ if key_padding_mask is not None:
319
+ assert key_padding_mask.shape == (bsz, src_len), \
320
+ f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
321
+ key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
322
+ expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
323
+ if attn_mask is None:
324
+ attn_mask = key_padding_mask
325
+ else:
326
+ attn_mask = attn_mask + key_padding_mask
327
+
328
+ # adjust dropout probability
329
+ if not training:
330
+ dropout_p = 0.0
331
+
332
+ #
333
+ # (deep breath) calculate attention and out projection
334
+ #
335
+
336
+ if need_weights:
337
+ B, Nt, E = q.shape
338
+ q_scaled = q / math.sqrt(E)
339
+
340
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
341
+
342
+ if attn_mask is not None:
343
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
344
+ else:
345
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
346
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
347
+ if dropout_p > 0.0:
348
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
349
+
350
+ attn_output = torch.bmm(attn_output_weights, v)
351
+
352
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
353
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
354
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
355
+
356
+ # optionally average attention weights over heads
357
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
358
+ if average_attn_weights:
359
+ attn_output_weights = attn_output_weights.mean(dim=1)
360
+
361
+ if not is_batched:
362
+ # squeeze the output if input was unbatched
363
+ attn_output = attn_output.squeeze(1)
364
+ attn_output_weights = attn_output_weights.squeeze(0)
365
+ return attn_output, attn_output_weights
366
+ else:
367
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
368
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
369
+ # in order to match the input for SDPA of (N, num_heads, L, S)
370
+ if attn_mask is not None:
371
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
372
+ attn_mask = attn_mask.unsqueeze(0)
373
+ else:
374
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
375
+
376
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
377
+ k = k.view(bsz, num_heads, src_len, head_dim)
378
+ v = v.view(bsz, num_heads, src_len, head_dim)
379
+
380
+ attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
381
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
382
+
383
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
384
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
385
+ if not is_batched:
386
+ # squeeze the output if input was unbatched
387
+ attn_output = attn_output.squeeze(1)
388
+ return attn_output, None
AR/modules/scaling.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
2
+ #
3
+ # See ../../../../LICENSE for clarification regarding multiple authors
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import logging
17
+ import math
18
+ import random
19
+ from typing import Optional
20
+ from typing import Tuple
21
+ from typing import Union
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ from torch import Tensor
26
+
27
+
28
+ class DoubleSwishFunction(torch.autograd.Function):
29
+ """
30
+ double_swish(x) = x * torch.sigmoid(x-1)
31
+ This is a definition, originally motivated by its close numerical
32
+ similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
33
+
34
+ Memory-efficient derivative computation:
35
+ double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
36
+ double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
37
+ Now, s'(x) = s(x) * (1-s(x)).
38
+ double_swish'(x) = x * s'(x) + s(x).
39
+ = x * s(x) * (1-s(x)) + s(x).
40
+ = double_swish(x) * (1-s(x)) + s(x)
41
+ ... so we just need to remember s(x) but not x itself.
42
+ """
43
+
44
+ @staticmethod
45
+ def forward(ctx, x: Tensor) -> Tensor:
46
+ requires_grad = x.requires_grad
47
+ x_dtype = x.dtype
48
+ if x.dtype == torch.float16:
49
+ x = x.to(torch.float32)
50
+
51
+ s = torch.sigmoid(x - 1.0)
52
+ y = x * s
53
+
54
+ if requires_grad:
55
+ deriv = y * (1 - s) + s
56
+ # notes on derivative of x * sigmoid(x - 1):
57
+ # https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
58
+ # min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
59
+ # max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
60
+ # the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
61
+ # floors), should be expectation-preserving.
62
+ floor = -0.043637
63
+ ceil = 1.2
64
+ d_scaled = (deriv - floor) * (255.0 / (ceil - floor)
65
+ ) + torch.rand_like(deriv)
66
+ if __name__ == "__main__":
67
+ # for self-testing only.
68
+ assert d_scaled.min() >= 0.0
69
+ assert d_scaled.max() < 256.0
70
+ d_int = d_scaled.to(torch.uint8)
71
+ ctx.save_for_backward(d_int)
72
+ if x.dtype == torch.float16 or torch.is_autocast_enabled():
73
+ y = y.to(torch.float16)
74
+ return y
75
+
76
+ @staticmethod
77
+ def backward(ctx, y_grad: Tensor) -> Tensor:
78
+ (d, ) = ctx.saved_tensors
79
+ # the same constants as used in forward pass.
80
+ floor = -0.043637
81
+ ceil = 1.2
82
+ d = d * ((ceil - floor) / 255.0) + floor
83
+ return y_grad * d
84
+
85
+
86
+ class DoubleSwish(torch.nn.Module):
87
+ def forward(self, x: Tensor) -> Tensor:
88
+ """Return double-swish activation function which is an approximation to Swish(Swish(x)),
89
+ that we approximate closely with x * sigmoid(x-1).
90
+ """
91
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
92
+ return x * torch.sigmoid(x - 1.0)
93
+ return DoubleSwishFunction.apply(x)
94
+
95
+
96
+ class ActivationBalancerFunction(torch.autograd.Function):
97
+ @staticmethod
98
+ def forward(
99
+ ctx,
100
+ x: Tensor,
101
+ scale_factor: Tensor,
102
+ sign_factor: Optional[Tensor],
103
+ channel_dim: int, ) -> Tensor:
104
+ if channel_dim < 0:
105
+ channel_dim += x.ndim
106
+ ctx.channel_dim = channel_dim
107
+ xgt0 = x > 0
108
+ if sign_factor is None:
109
+ ctx.save_for_backward(xgt0, scale_factor)
110
+ else:
111
+ ctx.save_for_backward(xgt0, scale_factor, sign_factor)
112
+ return x
113
+
114
+ @staticmethod
115
+ def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
116
+ if len(ctx.saved_tensors) == 3:
117
+ xgt0, scale_factor, sign_factor = ctx.saved_tensors
118
+ for _ in range(ctx.channel_dim, x_grad.ndim - 1):
119
+ scale_factor = scale_factor.unsqueeze(-1)
120
+ sign_factor = sign_factor.unsqueeze(-1)
121
+ factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
122
+ else:
123
+ xgt0, scale_factor = ctx.saved_tensors
124
+ for _ in range(ctx.channel_dim, x_grad.ndim - 1):
125
+ scale_factor = scale_factor.unsqueeze(-1)
126
+ factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
127
+ neg_delta_grad = x_grad.abs() * factor
128
+ return (x_grad - neg_delta_grad, None, None, None, )
129
+
130
+
131
+ def _compute_scale_factor(
132
+ x: Tensor,
133
+ channel_dim: int,
134
+ min_abs: float,
135
+ max_abs: float,
136
+ gain_factor: float,
137
+ max_factor: float, ) -> Tensor:
138
+ if channel_dim < 0:
139
+ channel_dim += x.ndim
140
+ sum_dims = [d for d in range(x.ndim) if d != channel_dim]
141
+ x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
142
+
143
+ if min_abs == 0.0:
144
+ below_threshold = 0.0
145
+ else:
146
+ # below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
147
+ # x_abs)_mean , min_abs.
148
+ below_threshold = (
149
+ (min_abs - x_abs_mean) * (gain_factor / min_abs)).clamp(
150
+ min=0, max=max_factor)
151
+
152
+ above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(
153
+ min=0, max=max_factor)
154
+
155
+ return below_threshold - above_threshold
156
+
157
+
158
+ def _compute_sign_factor(
159
+ x: Tensor,
160
+ channel_dim: int,
161
+ min_positive: float,
162
+ max_positive: float,
163
+ gain_factor: float,
164
+ max_factor: float, ) -> Tensor:
165
+ if channel_dim < 0:
166
+ channel_dim += x.ndim
167
+ sum_dims = [d for d in range(x.ndim) if d != channel_dim]
168
+ proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
169
+ if min_positive == 0.0:
170
+ factor1 = 0.0
171
+ else:
172
+ # 0 if proportion_positive >= min_positive, else can be
173
+ # as large as max_factor.
174
+ factor1 = ((min_positive - proportion_positive) *
175
+ (gain_factor / min_positive)).clamp_(
176
+ min=0, max=max_factor)
177
+
178
+ if max_positive == 1.0:
179
+ factor2 = 0.0
180
+ else:
181
+ # 0 if self.proportion_positive <= max_positive, else can be
182
+ # as large as -max_factor.
183
+ factor2 = ((proportion_positive - max_positive) *
184
+ (gain_factor / (1.0 - max_positive))).clamp_(
185
+ min=0, max=max_factor)
186
+ sign_factor = factor1 - factor2
187
+ # require min_positive != 0 or max_positive != 1:
188
+ assert not isinstance(sign_factor, float)
189
+ return sign_factor
190
+
191
+
192
+ class ActivationBalancer(torch.nn.Module):
193
+ """
194
+ Modifies the backpropped derivatives of a function to try to encourage, for
195
+ each channel, that it is positive at least a proportion `threshold` of the
196
+ time. It does this by multiplying negative derivative values by up to
197
+ (1+max_factor), and positive derivative values by up to (1-max_factor),
198
+ interpolated from 1 at the threshold to those extremal values when none
199
+ of the inputs are positive.
200
+
201
+ Args:
202
+ num_channels: the number of channels
203
+ channel_dim: the dimension/axis corresponding to the channel, e.g.
204
+ -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
205
+ min_positive: the minimum, per channel, of the proportion of the time
206
+ that (x > 0), below which we start to modify the derivatives.
207
+ max_positive: the maximum, per channel, of the proportion of the time
208
+ that (x > 0), above which we start to modify the derivatives.
209
+ max_factor: the maximum factor by which we modify the derivatives for
210
+ either the sign constraint or the magnitude constraint;
211
+ e.g. with max_factor=0.02, the the derivatives would be multiplied by
212
+ values in the range [0.98..1.02].
213
+ sign_gain_factor: determines the 'gain' with which we increase the
214
+ change in gradient once the constraints on min_positive and max_positive
215
+ are violated.
216
+ scale_gain_factor: determines the 'gain' with which we increase the
217
+ change in gradient once the constraints on min_abs and max_abs
218
+ are violated.
219
+ min_abs: the minimum average-absolute-value difference from the mean
220
+ value per channel, which we allow, before we start to modify
221
+ the derivatives to prevent this.
222
+ max_abs: the maximum average-absolute-value difference from the mean
223
+ value per channel, which we allow, before we start to modify
224
+ the derivatives to prevent this.
225
+ min_prob: determines the minimum probability with which we modify the
226
+ gradients for the {min,max}_positive and {min,max}_abs constraints,
227
+ on each forward(). This is done randomly to prevent all layers
228
+ from doing it at the same time. Early in training we may use
229
+ higher probabilities than this; it will decay to this value.
230
+ """
231
+
232
+ def __init__(
233
+ self,
234
+ num_channels: int,
235
+ channel_dim: int,
236
+ min_positive: float=0.05,
237
+ max_positive: float=0.95,
238
+ max_factor: float=0.04,
239
+ sign_gain_factor: float=0.01,
240
+ scale_gain_factor: float=0.02,
241
+ min_abs: float=0.2,
242
+ max_abs: float=100.0,
243
+ min_prob: float=0.1, ):
244
+ super(ActivationBalancer, self).__init__()
245
+ self.num_channels = num_channels
246
+ self.channel_dim = channel_dim
247
+ self.min_positive = min_positive
248
+ self.max_positive = max_positive
249
+ self.max_factor = max_factor
250
+ self.min_abs = min_abs
251
+ self.max_abs = max_abs
252
+ self.min_prob = min_prob
253
+ self.sign_gain_factor = sign_gain_factor
254
+ self.scale_gain_factor = scale_gain_factor
255
+
256
+ # count measures how many times the forward() function has been called.
257
+ # We occasionally sync this to a tensor called `count`, that exists to
258
+ # make sure it is synced to disk when we load and save the model.
259
+ self.cpu_count = 0
260
+ self.register_buffer("count", torch.tensor(0, dtype=torch.int64))
261
+
262
+ def forward(self, x: Tensor) -> Tensor:
263
+ if (torch.jit.is_scripting() or not x.requires_grad or
264
+ torch.jit.is_tracing()):
265
+ return _no_op(x)
266
+
267
+ count = self.cpu_count
268
+ self.cpu_count += 1
269
+
270
+ if random.random() < 0.01:
271
+ # Occasionally sync self.cpu_count with self.count.
272
+ # count affects the decay of 'prob'. don't do this on every iter,
273
+ # because syncing with the GPU is slow.
274
+ self.cpu_count = max(self.cpu_count, self.count.item())
275
+ self.count.fill_(self.cpu_count)
276
+
277
+ # the prob of doing some work exponentially decreases from 0.5 till it hits
278
+ # a floor at min_prob (==0.1, by default)
279
+ prob = max(self.min_prob, 0.5**(1 + (count / 4000.0)))
280
+
281
+ if random.random() < prob:
282
+ sign_gain_factor = 0.5
283
+ if self.min_positive != 0.0 or self.max_positive != 1.0:
284
+ sign_factor = _compute_sign_factor(
285
+ x,
286
+ self.channel_dim,
287
+ self.min_positive,
288
+ self.max_positive,
289
+ gain_factor=self.sign_gain_factor / prob,
290
+ max_factor=self.max_factor, )
291
+ else:
292
+ sign_factor = None
293
+
294
+ scale_factor = _compute_scale_factor(
295
+ x.detach(),
296
+ self.channel_dim,
297
+ min_abs=self.min_abs,
298
+ max_abs=self.max_abs,
299
+ gain_factor=self.scale_gain_factor / prob,
300
+ max_factor=self.max_factor, )
301
+ return ActivationBalancerFunction.apply(
302
+ x,
303
+ scale_factor,
304
+ sign_factor,
305
+ self.channel_dim, )
306
+ else:
307
+ return _no_op(x)
308
+
309
+
310
+ def BalancedDoubleSwish(d_model, channel_dim=-1, max_abs=10.0,
311
+ min_prob=0.25) -> nn.Sequential:
312
+ """
313
+ ActivationBalancer -> DoubleSwish
314
+ """
315
+ balancer = ActivationBalancer(
316
+ d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob)
317
+ return nn.Sequential(
318
+ balancer,
319
+ DoubleSwish(), )
AR/modules/transformer.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
2
+ import copy
3
+ import numbers
4
+ from functools import partial
5
+ from typing import Any
6
+ from typing import Callable
7
+ from typing import List
8
+ from typing import Optional
9
+ from typing import Tuple
10
+ from typing import Union
11
+
12
+ import torch
13
+ from AR.modules.activation import MultiheadAttention
14
+ from AR.modules.scaling import BalancedDoubleSwish
15
+ from torch import nn
16
+ from torch import Tensor
17
+ from torch.nn import functional as F
18
+
19
+ _shape_t = Union[int, List[int], torch.Size]
20
+
21
+
22
+ class LayerNorm(nn.Module):
23
+ __constants__ = ["normalized_shape", "eps", "elementwise_affine"]
24
+ normalized_shape: Tuple[int, ...]
25
+ eps: float
26
+ elementwise_affine: bool
27
+
28
+ def __init__(
29
+ self,
30
+ normalized_shape: _shape_t,
31
+ eps: float=1e-5,
32
+ elementwise_affine: bool=True,
33
+ device=None,
34
+ dtype=None, ) -> None:
35
+ factory_kwargs = {"device": device, "dtype": dtype}
36
+ super(LayerNorm, self).__init__()
37
+ if isinstance(normalized_shape, numbers.Integral):
38
+ # mypy error: incompatible types in assignment
39
+ normalized_shape = (normalized_shape, ) # type: ignore[assignment]
40
+ self.normalized_shape = tuple(
41
+ normalized_shape) # type: ignore[arg-type]
42
+ self.eps = eps
43
+ self.elementwise_affine = elementwise_affine
44
+ if self.elementwise_affine:
45
+ self.weight = nn.Parameter(
46
+ torch.empty(self.normalized_shape, **factory_kwargs))
47
+ self.bias = nn.Parameter(
48
+ torch.empty(self.normalized_shape, **factory_kwargs))
49
+ else:
50
+ self.register_parameter("weight", None)
51
+ self.register_parameter("bias", None)
52
+
53
+ self.reset_parameters()
54
+
55
+ def reset_parameters(self) -> None:
56
+ if self.elementwise_affine:
57
+ nn.init.ones_(self.weight)
58
+ nn.init.zeros_(self.bias)
59
+
60
+ def forward(self, input: Tensor, embedding: Any=None) -> Tensor:
61
+ if isinstance(input, tuple):
62
+ input, embedding = input
63
+ return (F.layer_norm(
64
+ input,
65
+ self.normalized_shape,
66
+ self.weight,
67
+ self.bias,
68
+ self.eps, ), embedding, )
69
+
70
+ assert embedding is None
71
+ return F.layer_norm(input, self.normalized_shape, self.weight,
72
+ self.bias, self.eps)
73
+
74
+ def extra_repr(self) -> str:
75
+ return (
76
+ "{normalized_shape}, eps={eps}, "
77
+ "elementwise_affine={elementwise_affine}".format(**self.__dict__))
78
+
79
+
80
+ class IdentityNorm(nn.Module):
81
+ def __init__(
82
+ self,
83
+ d_model: int,
84
+ eps: float=1e-5,
85
+ device=None,
86
+ dtype=None, ) -> None:
87
+ super(IdentityNorm, self).__init__()
88
+
89
+ def forward(self, input: Tensor, embedding: Any=None) -> Tensor:
90
+ if isinstance(input, tuple):
91
+ return input
92
+
93
+ assert embedding is None
94
+ return input
95
+
96
+
97
+ class TransformerEncoder(nn.Module):
98
+ r"""TransformerEncoder is a stack of N encoder layers. Users can build the
99
+ BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
100
+
101
+ Args:
102
+ encoder_layer: an instance of the TransformerEncoderLayer() class (required).
103
+ num_layers: the number of sub-encoder-layers in the encoder (required).
104
+ norm: the layer normalization component (optional).
105
+ enable_nested_tensor: if True, input will automatically convert to nested tensor
106
+ (and convert back on output). This will improve the overall performance of
107
+ TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
108
+
109
+ Examples::
110
+ >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
111
+ >>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
112
+ >>> src = torch.rand(10, 32, 512)
113
+ >>> out = transformer_encoder(src)
114
+ """
115
+ __constants__ = ["norm"]
116
+
117
+ def __init__(self, encoder_layer, num_layers, norm=None):
118
+ super(TransformerEncoder, self).__init__()
119
+ self.layers = _get_clones(encoder_layer, num_layers)
120
+ self.num_layers = num_layers
121
+ self.norm = norm
122
+
123
+ def forward(
124
+ self,
125
+ src: Tensor,
126
+ mask: Optional[Tensor]=None,
127
+ src_key_padding_mask: Optional[Tensor]=None,
128
+ return_layer_states: bool=False,cache=None ) -> Tensor:
129
+ r"""Pass the input through the encoder layers in turn.
130
+
131
+ Args:
132
+ src: the sequence to the encoder (required).
133
+ mask: the mask for the src sequence (optional).
134
+ src_key_padding_mask: the mask for the src keys per batch (optional).
135
+ return_layer_states: return layers' state (optional).
136
+
137
+ Shape:
138
+ see the docs in Transformer class.
139
+ """
140
+ if return_layer_states:
141
+ layer_states = [] # layers' output
142
+ output = src
143
+ for mod in self.layers:
144
+ output = mod(
145
+ output,
146
+ src_mask=mask,
147
+ src_key_padding_mask=src_key_padding_mask, cache=cache)
148
+ layer_states.append(output[0])
149
+
150
+ if self.norm is not None:
151
+ output = self.norm(output)
152
+
153
+ return layer_states, output
154
+
155
+ output = src
156
+ for mod in self.layers:
157
+ output = mod(output,
158
+ src_mask=mask,
159
+ src_key_padding_mask=src_key_padding_mask, cache=cache)
160
+
161
+ if self.norm is not None:
162
+ output = self.norm(output)
163
+
164
+ return output
165
+
166
+
167
+ class TransformerEncoderLayer(nn.Module):
168
+ __constants__ = ["batch_first", "norm_first"]
169
+
170
+ def __init__(
171
+ self,
172
+ d_model: int,
173
+ nhead: int,
174
+ dim_feedforward: int=2048,
175
+ dropout: float=0.1,
176
+ activation: Union[str, Callable[[Tensor], Tensor]]=F.relu,
177
+ batch_first: bool=False,
178
+ norm_first: bool=False,
179
+ device=None,
180
+ dtype=None,
181
+ linear1_self_attention_cls: nn.Module=nn.Linear,
182
+ linear2_self_attention_cls: nn.Module=nn.Linear,
183
+ linear1_feedforward_cls: nn.Module=nn.Linear,
184
+ linear2_feedforward_cls: nn.Module=nn.Linear,
185
+ layer_norm_cls: nn.Module=LayerNorm,
186
+ layer_norm_eps: float=1e-5,
187
+ adaptive_layer_norm=False, ) -> None:
188
+ factory_kwargs = {"device": device, "dtype": dtype}
189
+ super(TransformerEncoderLayer, self).__init__()
190
+ # print(233333333333,d_model,nhead)
191
+ # import os
192
+ # os._exit(2333333)
193
+ self.self_attn = MultiheadAttention(
194
+ d_model,#512 16
195
+ nhead,
196
+ dropout=dropout,
197
+ batch_first=batch_first,
198
+ linear1_cls=linear1_self_attention_cls,
199
+ linear2_cls=linear2_self_attention_cls,
200
+ **factory_kwargs, )
201
+
202
+ # Implementation of Feedforward model
203
+ self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward,
204
+ **factory_kwargs)
205
+ self.dropout = nn.Dropout(dropout)
206
+ self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model,
207
+ **factory_kwargs)
208
+
209
+ self.norm_first = norm_first
210
+ self.dropout1 = nn.Dropout(dropout)
211
+ self.dropout2 = nn.Dropout(dropout)
212
+
213
+ # Legacy string support for activation function.
214
+ if isinstance(activation, str):
215
+ activation = _get_activation_fn(activation)
216
+ elif isinstance(activation, partial):
217
+ activation = activation(d_model)
218
+ elif activation == BalancedDoubleSwish:
219
+ activation = BalancedDoubleSwish(d_model)
220
+
221
+ # # We can't test self.activation in forward() in TorchScript,
222
+ # # so stash some information about it instead.
223
+ # if activation is F.relu or isinstance(activation, torch.nn.ReLU):
224
+ # self.activation_relu_or_gelu = 1
225
+ # elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
226
+ # self.activation_relu_or_gelu = 2
227
+ # else:
228
+ # self.activation_relu_or_gelu = 0
229
+ self.activation = activation
230
+
231
+ norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
232
+ if layer_norm_cls == IdentityNorm:
233
+ norm2 = BalancedBasicNorm(
234
+ d_model, eps=layer_norm_eps, **factory_kwargs)
235
+ else:
236
+ norm2 = layer_norm_cls(
237
+ d_model, eps=layer_norm_eps, **factory_kwargs)
238
+
239
+ if adaptive_layer_norm:
240
+ self.norm1 = AdaptiveLayerNorm(d_model, norm1)
241
+ self.norm2 = AdaptiveLayerNorm(d_model, norm2)
242
+ else:
243
+ self.norm1 = norm1
244
+ self.norm2 = norm2
245
+
246
+ def __setstate__(self, state):
247
+ super(TransformerEncoderLayer, self).__setstate__(state)
248
+ if not hasattr(self, "activation"):
249
+ self.activation = F.relu
250
+
251
+ def forward(
252
+ self,
253
+ src: Tensor,
254
+ src_mask: Optional[Tensor]=None,
255
+ src_key_padding_mask: Optional[Tensor]=None,cache=None ) -> Tensor:
256
+ r"""Pass the input through the encoder layer.
257
+
258
+ Args:
259
+ src: the sequence to the encoder layer (required).
260
+ src_mask: the mask for the src sequence (optional).
261
+ src_key_padding_mask: the mask for the src keys per batch (optional).
262
+
263
+ Shape:
264
+ see the docs in Transformer class.
265
+ """
266
+ x, stage_embedding = src, None
267
+ is_src_tuple = False
268
+ if isinstance(src, tuple):
269
+ x, stage_embedding = src
270
+ is_src_tuple = True
271
+
272
+ if src_key_padding_mask is not None:
273
+ _skpm_dtype = src_key_padding_mask.dtype
274
+ if _skpm_dtype != torch.bool and not torch.is_floating_point(
275
+ src_key_padding_mask):
276
+ raise AssertionError(
277
+ "only bool and floating types of key_padding_mask are supported"
278
+ )
279
+
280
+ if self.norm_first:
281
+ x = x + self._sa_block(
282
+ self.norm1(x, stage_embedding),
283
+ src_mask,
284
+ src_key_padding_mask,cache=cache )
285
+ x = x + self._ff_block(self.norm2(x, stage_embedding))
286
+ else:
287
+ x = self.norm1(
288
+ x + self._sa_block(x, src_mask, src_key_padding_mask,cache=cache),
289
+ stage_embedding, )
290
+ x = self.norm2(x + self._ff_block(x), stage_embedding)
291
+
292
+ if is_src_tuple:
293
+ return (x, stage_embedding)
294
+ return x
295
+
296
+ # self-attention block
297
+ def _sa_block(
298
+ self,
299
+ x: Tensor,
300
+ attn_mask: Optional[Tensor],
301
+ key_padding_mask: Optional[Tensor],cache=None ) -> Tensor:
302
+ # print(x.shape,attn_mask.shape,key_padding_mask)
303
+ #torch.Size([1, 188, 512]) torch.Size([188, 188]) None
304
+ # import os
305
+ # os._exit(23333)
306
+ x = self.self_attn(
307
+ x,
308
+ x,
309
+ x,
310
+ attn_mask=attn_mask,
311
+ key_padding_mask=key_padding_mask,
312
+ need_weights=False,cache=cache )[0]
313
+ return self.dropout1(x)
314
+
315
+ # feed forward block
316
+ def _ff_block(self, x: Tensor) -> Tensor:
317
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
318
+ return self.dropout2(x)
319
+
320
+
321
+ class AdaptiveLayerNorm(nn.Module):
322
+ r"""Adaptive Layer Normalization"""
323
+
324
+ def __init__(self, d_model, norm) -> None:
325
+ super(AdaptiveLayerNorm, self).__init__()
326
+ self.project_layer = nn.Linear(d_model, 2 * d_model)
327
+ self.norm = norm
328
+ self.d_model = d_model
329
+ self.eps = self.norm.eps
330
+
331
+ def forward(self, input: Tensor, embedding: Tensor=None) -> Tensor:
332
+ if isinstance(input, tuple):
333
+ input, embedding = input
334
+ weight, bias = torch.split(
335
+ self.project_layer(embedding),
336
+ split_size_or_sections=self.d_model,
337
+ dim=-1, )
338
+ return (weight * self.norm(input) + bias, embedding)
339
+
340
+ weight, bias = torch.split(
341
+ self.project_layer(embedding),
342
+ split_size_or_sections=self.d_model,
343
+ dim=-1, )
344
+ return weight * self.norm(input) + bias
345
+
346
+ def _get_clones(module, N):
347
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
AR/text_processing/__init__.py ADDED
File without changes
AR/text_processing/phonemizer.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/text_processing/phonemizer.py
2
+ import itertools
3
+ import re
4
+ from typing import Dict
5
+ from typing import List
6
+
7
+ import regex
8
+ from gruut import sentences
9
+ from gruut.const import Sentence
10
+ from gruut.const import Word
11
+ from AR.text_processing.symbols import SYMBOL_TO_ID
12
+
13
+
14
+ class GruutPhonemizer:
15
+ def __init__(self, language: str):
16
+ self._phonemizer = sentences
17
+ self.lang = language
18
+ self.symbol_to_id = SYMBOL_TO_ID
19
+ self._special_cases_dict: Dict[str] = {
20
+ r"\.\.\.": "... ",
21
+ ";": "; ",
22
+ ":": ": ",
23
+ ",": ", ",
24
+ r"\.": ". ",
25
+ "!": "! ",
26
+ r"\?": "? ",
27
+ "—": "—",
28
+ "…": "… ",
29
+ "«": "«",
30
+ "»": "»"
31
+ }
32
+ self._punctuation_regexp: str = rf"([{''.join(self._special_cases_dict.keys())}])"
33
+
34
+ def _normalize_punctuation(self, text: str) -> str:
35
+ text = regex.sub(fr"\pZ+{self._punctuation_regexp}", r"\1", text)
36
+ text = regex.sub(fr"{self._punctuation_regexp}(\pL)", r"\1 \2", text)
37
+ text = regex.sub(r"\pZ+", r" ", text)
38
+ return text.strip()
39
+
40
+ def _convert_punctuation(self, word: Word) -> str:
41
+ if not word.phonemes:
42
+ return ''
43
+ if word.phonemes[0] in ['‖', '|']:
44
+ return word.text.strip()
45
+
46
+ phonemes = ''.join(word.phonemes)
47
+ # remove modifier characters ˈˌː with regex
48
+ phonemes = re.sub(r'[ˈˌː͡]', '', phonemes)
49
+ return phonemes.strip()
50
+
51
+ def phonemize(self, text: str, espeak: bool=False) -> str:
52
+ text_to_phonemize: str = self._normalize_punctuation(text)
53
+ sents: List[Sentence] = [
54
+ sent
55
+ for sent in self._phonemizer(
56
+ text_to_phonemize, lang="en-us", espeak=espeak)
57
+ ]
58
+ words: List[str] = [
59
+ self._convert_punctuation(word) for word in itertools.chain(*sents)
60
+ ]
61
+ return ' '.join(words)
62
+
63
+ def transform(self, phonemes):
64
+ # convert phonemes to ids
65
+ # dictionary is in symbols.py
66
+ return [
67
+ self.symbol_to_id[p] for p in phonemes
68
+ if p in self.symbol_to_id.keys()
69
+ ]
70
+
71
+
72
+ if __name__ == "__main__":
73
+ phonemizer = GruutPhonemizer("en-us")
74
+ # text -> IPA
75
+ phonemes = phonemizer.phonemize("Hello, wor-ld ?")
76
+ print("phonemes:", phonemes)
77
+ print("len(phonemes):", len(phonemes))
78
+ phoneme_ids = phonemizer.transform(phonemes)
79
+ print("phoneme_ids:", phoneme_ids)
80
+ print("len(phoneme_ids):", len(phoneme_ids))
AR/text_processing/symbols.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/text_processing/symbols.py
2
+ PAD = '_'
3
+ PUNCTUATION = ';:,.!?¡¿—…"«»“” '
4
+ LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
5
+ IPA_LETTERS = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
6
+ SYMBOLS = [PAD] + list(PUNCTUATION) + list(LETTERS) + list(IPA_LETTERS)
7
+ SPACE_ID = SYMBOLS.index(" ")
8
+ SYMBOL_TO_ID = {s: i for i, s in enumerate(SYMBOLS)}
9
+ ID_TO_SYMBOL = {i: s for i, s in enumerate(SYMBOLS)}
AR/utils/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+
4
+ def str2bool(str):
5
+ return True if str.lower() == 'true' else False
6
+
7
+
8
+ def get_newest_ckpt(string_list):
9
+ # 定义一个正则表达式模式,用于匹配字符串中的数字
10
+ pattern = r'epoch=(\d+)-step=(\d+)\.ckpt'
11
+
12
+ # 使用正则表达式提取每个字符串中的数字信息,并创建一个包含元组的列表
13
+ extracted_info = []
14
+ for string in string_list:
15
+ match = re.match(pattern, string)
16
+ if match:
17
+ epoch = int(match.group(1))
18
+ step = int(match.group(2))
19
+ extracted_info.append((epoch, step, string))
20
+ # 按照 epoch 后面的数字和 step 后面的数字进行排序
21
+ sorted_info = sorted(
22
+ extracted_info, key=lambda x: (x[0], x[1]), reverse=True)
23
+ # 获取最新的 ckpt 文件名
24
+ newest_ckpt = sorted_info[0][2]
25
+ return newest_ckpt
26
+
27
+
28
+ # 文本存在且不为空时 return True
29
+ def check_txt_file(file_path):
30
+ try:
31
+ with open(file_path, 'r') as file:
32
+ text = file.readline().strip()
33
+ assert text.strip() != ''
34
+ return text
35
+ except Exception:
36
+ return False
37
+ return False
AR/utils/initialize.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Initialize modules for espnet2 neural networks."""
3
+ import torch
4
+ from typeguard import check_argument_types
5
+
6
+
7
+ def initialize(model: torch.nn.Module, init: str):
8
+ """Initialize weights of a neural network module.
9
+
10
+ Parameters are initialized using the given method or distribution.
11
+
12
+ Custom initialization routines can be implemented into submodules
13
+ as function `espnet_initialization_fn` within the custom module.
14
+
15
+ Args:
16
+ model: Target.
17
+ init: Method of initialization.
18
+ """
19
+ assert check_argument_types()
20
+ print("init with", init)
21
+
22
+ # weight init
23
+ for p in model.parameters():
24
+ if p.dim() > 1:
25
+ if init == "xavier_uniform":
26
+ torch.nn.init.xavier_uniform_(p.data)
27
+ elif init == "xavier_normal":
28
+ torch.nn.init.xavier_normal_(p.data)
29
+ elif init == "kaiming_uniform":
30
+ torch.nn.init.kaiming_uniform_(p.data, nonlinearity="relu")
31
+ elif init == "kaiming_normal":
32
+ torch.nn.init.kaiming_normal_(p.data, nonlinearity="relu")
33
+ else:
34
+ raise ValueError("Unknown initialization: " + init)
35
+ # bias init
36
+ for name, p in model.named_parameters():
37
+ if ".bias" in name and p.dim() == 1:
38
+ p.data.zero_()
AR/utils/io.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ import yaml
5
+
6
+
7
+ def load_yaml_config(path):
8
+ with open(path) as f:
9
+ config = yaml.full_load(f)
10
+ return config
11
+
12
+
13
+ def save_config_to_yaml(config, path):
14
+ assert path.endswith('.yaml')
15
+ with open(path, 'w') as f:
16
+ f.write(yaml.dump(config))
17
+ f.close()
18
+
19
+
20
+ def write_args(args, path):
21
+ args_dict = dict((name, getattr(args, name)) for name in dir(args)
22
+ if not name.startswith('_'))
23
+ with open(path, 'a') as args_file:
24
+ args_file.write('==> torch version: {}\n'.format(torch.__version__))
25
+ args_file.write(
26
+ '==> cudnn version: {}\n'.format(torch.backends.cudnn.version()))
27
+ args_file.write('==> Cmd:\n')
28
+ args_file.write(str(sys.argv))
29
+ args_file.write('\n==> args:\n')
30
+ for k, v in sorted(args_dict.items()):
31
+ args_file.write(' %s: %s\n' % (str(k), str(v)))
32
+ args_file.close()
app.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ cnhubert_base_path = "pretrained_models/chinese-hubert-base"
3
+ bert_path = "pretrained_models/chinese-roberta-wwm-ext-large"
4
+
5
+ import gradio as gr
6
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
7
+ import sys,torch,numpy as np
8
+ from pathlib import Path
9
+ import os,pdb,utils,librosa,math,traceback,requests,argparse,torch,multiprocessing,pandas as pd,torch.multiprocessing as mp,soundfile
10
+ # torch.backends.cuda.sdp_kernel("flash")
11
+ # torch.backends.cuda.enable_flash_sdp(True)
12
+ # torch.backends.cuda.enable_mem_efficient_sdp(True) # Not avaliable if torch version is lower than 2.0
13
+ # torch.backends.cuda.enable_math_sdp(True)
14
+ from random import shuffle
15
+ from AR.utils import get_newest_ckpt
16
+ from glob import glob
17
+ from tqdm import tqdm
18
+ from feature_extractor import cnhubert
19
+ cnhubert.cnhubert_base_path=cnhubert_base_path
20
+ from io import BytesIO
21
+ from module.models import SynthesizerTrn
22
+ from AR.models.t2s_lightning_module import Text2SemanticLightningModule
23
+ from AR.utils.io import load_yaml_config
24
+ from text import cleaned_text_to_sequence
25
+ from text.cleaner import text_to_sequence, clean_text
26
+ from time import time as ttime
27
+ from module.mel_processing import spectrogram_torch
28
+ from my_utils import load_audio
29
+
30
+ import logging
31
+ logging.getLogger('httpx').setLevel(logging.WARNING)
32
+ logging.getLogger('httpcore').setLevel(logging.WARNING)
33
+ logging.getLogger('multipart').setLevel(logging.WARNING)
34
+
35
+ device = "cpu"
36
+ is_half = False
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(bert_path)
39
+ bert_model=AutoModelForMaskedLM.from_pretrained(bert_path)
40
+ if(is_half==True):bert_model=bert_model.half().to(device)
41
+ else:bert_model=bert_model.to(device)
42
+ # bert_model=bert_model.to(device)
43
+ def get_bert_feature(text, word2ph):
44
+ with torch.no_grad():
45
+ inputs = tokenizer(text, return_tensors="pt")
46
+ for i in inputs:
47
+ inputs[i] = inputs[i].to(device)#####输入是long不用管精度问题,精度随bert_model
48
+ res = bert_model(**inputs, output_hidden_states=True)
49
+ res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
50
+ assert len(word2ph) == len(text)
51
+ phone_level_feature = []
52
+ for i in range(len(word2ph)):
53
+ repeat_feature = res[i].repeat(word2ph[i], 1)
54
+ phone_level_feature.append(repeat_feature)
55
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
56
+ # if(is_half==True):phone_level_feature=phone_level_feature.half()
57
+ return phone_level_feature.T
58
+
59
+
60
+ def load_model(sovits_path, gpt_path):
61
+ n_semantic = 1024
62
+ dict_s2 = torch.load(sovits_path, map_location="cpu")
63
+ hps = dict_s2["config"]
64
+
65
+ class DictToAttrRecursive:
66
+ def __init__(self, input_dict):
67
+ for key, value in input_dict.items():
68
+ if isinstance(value, dict):
69
+ # 如果值是字典,递归调用构造函数
70
+ setattr(self, key, DictToAttrRecursive(value))
71
+ else:
72
+ setattr(self, key, value)
73
+
74
+ hps = DictToAttrRecursive(hps)
75
+ hps.model.semantic_frame_rate = "25hz"
76
+ dict_s1 = torch.load(gpt_path, map_location="cpu")
77
+ config = dict_s1["config"]
78
+ ssl_model = cnhubert.get_model()
79
+ if (is_half == True):
80
+ ssl_model = ssl_model.half().to(device)
81
+ else:
82
+ ssl_model = ssl_model.to(device)
83
+
84
+ vq_model = SynthesizerTrn(
85
+ hps.data.filter_length // 2 + 1,
86
+ hps.train.segment_size // hps.data.hop_length,
87
+ n_speakers=hps.data.n_speakers,
88
+ **hps.model)
89
+ if (is_half == True):
90
+ vq_model = vq_model.half().to(device)
91
+ else:
92
+ vq_model = vq_model.to(device)
93
+ vq_model.eval()
94
+ vq_model.load_state_dict(dict_s2["weight"], strict=False)
95
+ hz = 50
96
+ max_sec = config['data']['max_sec']
97
+ # t2s_model = Text2SemanticLightningModule.load_from_checkpoint(checkpoint_path=gpt_path, config=config, map_location="cpu")#########todo
98
+ t2s_model = Text2SemanticLightningModule(config, "ojbk", is_train=False)
99
+ t2s_model.load_state_dict(dict_s1["weight"])
100
+ if (is_half == True): t2s_model = t2s_model.half()
101
+ t2s_model = t2s_model.to(device)
102
+ t2s_model.eval()
103
+ total = sum([param.nelement() for param in t2s_model.parameters()])
104
+ print("Number of parameter: %.2fM" % (total / 1e6))
105
+ return vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
106
+
107
+
108
+ def get_spepc(hps, filename):
109
+ audio=load_audio(filename,int(hps.data.sampling_rate))
110
+ audio=torch.FloatTensor(audio)
111
+ audio_norm = audio
112
+ audio_norm = audio_norm.unsqueeze(0)
113
+ spec = spectrogram_torch(audio_norm, hps.data.filter_length,hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,center=False)
114
+ return spec
115
+
116
+
117
+ def create_tts_fn(vq_model, ssl_model, t2s_model, hps, config, hz, max_sec):
118
+ def tts_fn(ref_wav_path, prompt_text, prompt_language, text, text_language):
119
+ t0 = ttime()
120
+ prompt_text=prompt_text.strip("\n")
121
+ prompt_language,text=prompt_language,text.strip("\n")
122
+ print(text)
123
+ if len(text) > 50:
124
+ return f"Error: Text is too long, ({len(text)}>50)", None
125
+ with torch.no_grad():
126
+ wav16k, sr = librosa.load(ref_wav_path, sr=16000) # 派蒙
127
+ wav16k = torch.from_numpy(wav16k)
128
+ if(is_half==True):wav16k=wav16k.half().to(device)
129
+ else:wav16k=wav16k.to(device)
130
+ ssl_content = ssl_model.model(wav16k.unsqueeze(0))["last_hidden_state"].transpose(1, 2)#.float()
131
+ codes = vq_model.extract_latent(ssl_content)
132
+ prompt_semantic = codes[0, 0]
133
+ t1 = ttime()
134
+ phones1, word2ph1, norm_text1 = clean_text(prompt_text, prompt_language)
135
+ phones1=cleaned_text_to_sequence(phones1)
136
+ texts=text.split("\n")
137
+ audio_opt = []
138
+ zero_wav=np.zeros(int(hps.data.sampling_rate*0.3),dtype=np.float16 if is_half==True else np.float32)
139
+ for text in texts:
140
+ phones2, word2ph2, norm_text2 = clean_text(text, text_language)
141
+ phones2 = cleaned_text_to_sequence(phones2)
142
+ if(prompt_language=="zh"):bert1 = get_bert_feature(norm_text1, word2ph1).to(device)
143
+ else:bert1 = torch.zeros((1024, len(phones1)),dtype=torch.float16 if is_half==True else torch.float32).to(device)
144
+ if(text_language=="zh"):bert2 = get_bert_feature(norm_text2, word2ph2).to(device)
145
+ else:bert2 = torch.zeros((1024, len(phones2))).to(bert1)
146
+ bert = torch.cat([bert1, bert2], 1)
147
+
148
+ all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)
149
+ bert = bert.to(device).unsqueeze(0)
150
+ all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
151
+ prompt = prompt_semantic.unsqueeze(0).to(device)
152
+ t2 = ttime()
153
+ with torch.no_grad():
154
+ # pred_semantic = t2s_model.model.infer(
155
+ pred_semantic,idx = t2s_model.model.infer_panel(
156
+ all_phoneme_ids,
157
+ all_phoneme_len,
158
+ prompt,
159
+ bert,
160
+ # prompt_phone_len=ph_offset,
161
+ top_k=config['inference']['top_k'],
162
+ early_stop_num=hz * max_sec)
163
+ t3 = ttime()
164
+ # print(pred_semantic.shape,idx)
165
+ pred_semantic = pred_semantic[:,-idx:].unsqueeze(0) # .unsqueeze(0)#mq要多unsqueeze一次
166
+ refer = get_spepc(hps, ref_wav_path)#.to(device)
167
+ if(is_half==True):refer=refer.half().to(device)
168
+ else:refer=refer.to(device)
169
+ # audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]
170
+ audio = vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer).detach().cpu().numpy()[0, 0]###试试重建不带上prompt部分
171
+ audio_opt.append(audio)
172
+ audio_opt.append(zero_wav)
173
+ t4 = ttime()
174
+ print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
175
+ return "Success", (hps.data.sampling_rate,(np.concatenate(audio_opt,0)*32768).astype(np.int16))
176
+ return tts_fn
177
+
178
+
179
+ splits={",","。","?","!",",",".","?","!","~",":",":","—","…",}#不考虑省略号
180
+ def split(todo_text):
181
+ todo_text = todo_text.replace("……", "。").replace("——", ",")
182
+ if (todo_text[-1] not in splits): todo_text += "。"
183
+ i_split_head = i_split_tail = 0
184
+ len_text = len(todo_text)
185
+ todo_texts = []
186
+ while (1):
187
+ if (i_split_head >= len_text): break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
188
+ if (todo_text[i_split_head] in splits):
189
+ i_split_head += 1
190
+ todo_texts.append(todo_text[i_split_tail:i_split_head])
191
+ i_split_tail = i_split_head
192
+ else:
193
+ i_split_head += 1
194
+ return todo_texts
195
+
196
+
197
+ def change_reference_audio(prompt_text, transcripts):
198
+ return transcripts[prompt_text]
199
+
200
+
201
+ models = []
202
+ models_info = {
203
+ "alice": {
204
+ "gpt_weight": "blue_archive/alice/alice-e15.ckpt",
205
+ "sovits_weight": "blue_archive/alice/alice_e8_s216.pth",
206
+ "title": "Blue Archive-天童アリス",
207
+ "example_reference": "召喚にお応じろ!ゴーレムよ!主人の命令に従い!"
208
+ },
209
+ "yuuka": {
210
+ "gpt_weight": "blue_archive/yuuka/yuuka-e15.ckpt",
211
+ "sovits_weight": "blue_archive/yuuka/yuuka_e8_s208.pth",
212
+ "title": "Blue Archive-早瀬ユウカ",
213
+ "example_reference": "せ~ん~せ~い~。もう少し頑張ってください!"
214
+ },
215
+ "mika": {
216
+ "gpt_weight": "blue_archive/mika/mika-e15.ckpt",
217
+ "sovits_weight": "blue_archive/mika/mika_e8_s176.pth",
218
+ "title": "Blue Archive-聖園ミカ",
219
+ "example_reference": "あけましておめでとう、先生!こ��な私だけど、今年もよろしくね☆"
220
+ }
221
+ }
222
+ for i, info in models_info.items():
223
+ title = info['title']
224
+ cover = f"blue_archive/{i}/tachie.png"
225
+ gpt_weight = info['gpt_weight']
226
+ sovits_weight = info['sovits_weight']
227
+ example_reference = info['example_reference']
228
+ transcripts = {}
229
+ with open(f"blue_archive/{i}/reference_audio/transcript.txt", 'r', encoding='utf-8') as file:
230
+ for line in file:
231
+ line = line.strip()
232
+ wav, t = line.split("|")
233
+ transcripts[t] = os.path.join(f"blue_archive/{i}/reference_audio", wav)
234
+
235
+ vq_model, ssl_model, t2s_model, hps, config, hz, max_sec = load_model(sovits_weight, gpt_weight)
236
+
237
+
238
+ models.append(
239
+ (
240
+ i,
241
+ title,
242
+ cover,
243
+ transcripts,
244
+ example_reference,
245
+ create_tts_fn(
246
+ vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
247
+ )
248
+ )
249
+ )
250
+ with gr.Blocks() as app:
251
+ gr.Markdown(
252
+ "# <center> GPT-SoVITS \n"
253
+ "## <center> https://github.com/RVC-Boss/GPT-SoVITS\n"
254
+
255
+ )
256
+ with gr.Tabs():
257
+ for (name, title, cover, transcripts, example_reference, tts_fn) in models:
258
+ with gr.TabItem(name):
259
+ with gr.Row():
260
+ gr.Markdown(
261
+ '<div align="center">'
262
+ f'<a><strong>{title}</strong></a>'
263
+ f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else ""
264
+ '</div>'
265
+ )
266
+ with gr.Row():
267
+ with gr.Column():
268
+ prompt_text = gr.Dropdown(
269
+ label="Transcript of the Reference Audio",
270
+ value=example_reference,
271
+ choices=transcripts.keys()
272
+ )
273
+ inp_ref_audio = gr.Audio(
274
+ label="Reference Audio",
275
+ type="filepath",
276
+ interactive=False,
277
+ value=transcripts[example_reference]
278
+ )
279
+ transcripts_state = gr.State(value=transcripts)
280
+ prompt_text.change(
281
+ fn=change_reference_audio,
282
+ inputs=[prompt_text, transcripts_state],
283
+ outputs=[inp_ref_audio]
284
+ )
285
+ prompt_language = gr.State(value="ja")
286
+ with gr.Column():
287
+ text = gr.Textbox(label="Input Text", value="はいきなり、春の嵐のように突然訪れた。")
288
+ text_language = gr.Dropdown(
289
+ label="Language",
290
+ choices=["zh", "en", "ja"],
291
+ value="ja"
292
+ )
293
+ inference_button = gr.Button("Generate", variant="primary")
294
+ om = gr.Textbox(label="Output Message")
295
+ output = gr.Audio(label="Output Audio")
296
+ inference_button.click(
297
+ fn=tts_fn,
298
+ inputs=[inp_ref_audio, prompt_text, prompt_language, text, text_language],
299
+ outputs=[om, output],
300
+ concurrency_limit=1
301
+ )
302
+
303
+ app.queue(max_size=30).launch()
blue_archive/alice/alice-e15.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3950747914316e1aefbf2890f897c6215406444c161af7781e005dead1c00c6
3
+ size 155084922
blue_archive/alice/alice_e8_s216.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e47be4af5ae052a694a1d14b2490a79b875d6a772d78b399d9309a8eb7be787f
3
+ size 84929166
blue_archive/mika/mika-e15.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5bd21be12a5957a439ad3a1d229df46eefa29cca816bdf570d8ae051146ac34
3
+ size 155084623
blue_archive/mika/mika_e8_s176.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ea13758fd1535e8039729e21c61e048cd8bf8d2fa0bed04f0d258bb593969d0
3
+ size 84928425
blue_archive/yuuka/yuuka-e15.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:495027278e3ce833b1be00662fbaf360f8f7e985c9d7153a369d53aebeafc50c
3
+ size 155084922
blue_archive/yuuka/yuuka_e8_s208.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f165a2eaf4ee15f8f838186a4fd01c62fc089a34d1693f7ec823db12f47927c
3
+ size 84929166
feature_extractor/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from . import cnhubert, whisper_enc
2
+
3
+ content_module_map = {
4
+ 'cnhubert': cnhubert,
5
+ 'whisper': whisper_enc
6
+ }
feature_extractor/cnhubert.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ import librosa
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import soundfile as sf
7
+ import logging
8
+
9
+ logging.getLogger("numba").setLevel(logging.WARNING)
10
+
11
+ from transformers import (
12
+ Wav2Vec2FeatureExtractor,
13
+ HubertModel,
14
+ Wav2Vec2Model,
15
+ )
16
+
17
+ import utils
18
+ import torch.nn as nn
19
+
20
+ cnhubert_base_path=None
21
+ class CNHubert(nn.Module):
22
+ def __init__(self):
23
+ super().__init__()
24
+ self.model = HubertModel.from_pretrained(cnhubert_base_path)
25
+ self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(cnhubert_base_path)
26
+ def forward(self, x):
27
+ input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
28
+ feats = self.model(input_values)["last_hidden_state"]
29
+ return feats
30
+
31
+ # class CNHubertLarge(nn.Module):
32
+ # def __init__(self):
33
+ # super().__init__()
34
+ # self.model = HubertModel.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
35
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
36
+ # def forward(self, x):
37
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
38
+ # feats = self.model(input_values)["last_hidden_state"]
39
+ # return feats
40
+ #
41
+ # class CVec(nn.Module):
42
+ # def __init__(self):
43
+ # super().__init__()
44
+ # self.model = HubertModel.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
45
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
46
+ # def forward(self, x):
47
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
48
+ # feats = self.model(input_values)["last_hidden_state"]
49
+ # return feats
50
+ #
51
+ # class cnw2v2base(nn.Module):
52
+ # def __init__(self):
53
+ # super().__init__()
54
+ # self.model = Wav2Vec2Model.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
55
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
56
+ # def forward(self, x):
57
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
58
+ # feats = self.model(input_values)["last_hidden_state"]
59
+ # return feats
60
+
61
+
62
+
63
+ def get_model():
64
+ model = CNHubert()
65
+ model.eval()
66
+ return model
67
+
68
+ # def get_large_model():
69
+ # model = CNHubertLarge()
70
+ # model.eval()
71
+ # return model
72
+ #
73
+ # def get_model_cvec():
74
+ # model = CVec()
75
+ # model.eval()
76
+ # return model
77
+ #
78
+ # def get_model_cnw2v2base():
79
+ # model = cnw2v2base()
80
+ # model.eval()
81
+ # return model
82
+
83
+ def get_content(hmodel, wav_16k_tensor):
84
+ with torch.no_grad():
85
+ feats = hmodel(wav_16k_tensor)
86
+ return feats.transpose(1,2)
87
+
88
+
89
+ if __name__ == '__main__':
90
+ model = get_model()
91
+ src_path = "/Users/Shared/原音频2.wav"
92
+ wav_16k_tensor = utils.load_wav_to_torch_and_resample(src_path, 16000)
93
+ model = model
94
+ wav_16k_tensor = wav_16k_tensor
95
+ feats = get_content(model,wav_16k_tensor)
96
+ print(feats.shape)
97
+
feature_extractor/whisper_enc.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_model():
5
+ import whisper
6
+ model = whisper.load_model("small", device='cpu')
7
+
8
+ return model.encoder
9
+
10
+
11
+ def get_content(model=None, wav_16k_tensor=None):
12
+ from whisper import log_mel_spectrogram, pad_or_trim
13
+ dev = next(model.parameters()).device
14
+ mel = log_mel_spectrogram(wav_16k_tensor).to(dev)[:, :3000]
15
+ # if torch.cuda.is_available():
16
+ # mel = mel.to(torch.float16)
17
+ feature_len = mel.shape[-1] // 2
18
+ assert mel.shape[-1] < 3000, "输入音频过长,只允许输入30以内音频"
19
+ with torch.no_grad():
20
+ feature = model(pad_or_trim(mel, 3000).unsqueeze(0))[:1, :feature_len, :].transpose(1,2)
21
+ return feature
22
+
module/__init__.py ADDED
File without changes
module/attentions.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from module import commons
7
+ from module. modules import LayerNorm
8
+
9
+
10
+ class Encoder(nn.Module):
11
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4,isflow=False, **kwargs):
12
+ super().__init__()
13
+ self.hidden_channels = hidden_channels
14
+ self.filter_channels = filter_channels
15
+ self.n_heads = n_heads
16
+ self.n_layers = n_layers
17
+ self.kernel_size = kernel_size
18
+ self.p_dropout = p_dropout
19
+ self.window_size = window_size
20
+
21
+ self.drop = nn.Dropout(p_dropout)
22
+ self.attn_layers = nn.ModuleList()
23
+ self.norm_layers_1 = nn.ModuleList()
24
+ self.ffn_layers = nn.ModuleList()
25
+ self.norm_layers_2 = nn.ModuleList()
26
+ for i in range(self.n_layers):
27
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
28
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
29
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
30
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
31
+ if isflow:
32
+ cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2*hidden_channels*n_layers, 1)
33
+ self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
34
+ self.cond_layer = weight_norm_modules(cond_layer, name='weight')
35
+ self.gin_channels = kwargs["gin_channels"]
36
+ def forward(self, x, x_mask, g=None):
37
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
38
+ x = x * x_mask
39
+ if g is not None:
40
+ g = self.cond_layer(g)
41
+
42
+ for i in range(self.n_layers):
43
+ if g is not None:
44
+ x = self.cond_pre(x)
45
+ cond_offset = i * 2 * self.hidden_channels
46
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
47
+ x = commons.fused_add_tanh_sigmoid_multiply(
48
+ x,
49
+ g_l,
50
+ torch.IntTensor([self.hidden_channels]))
51
+ y = self.attn_layers[i](x, x, attn_mask)
52
+ y = self.drop(y)
53
+ x = self.norm_layers_1[i](x + y)
54
+
55
+ y = self.ffn_layers[i](x, x_mask)
56
+ y = self.drop(y)
57
+ x = self.norm_layers_2[i](x + y)
58
+ x = x * x_mask
59
+ return x
60
+
61
+
62
+ class Decoder(nn.Module):
63
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
64
+ super().__init__()
65
+ self.hidden_channels = hidden_channels
66
+ self.filter_channels = filter_channels
67
+ self.n_heads = n_heads
68
+ self.n_layers = n_layers
69
+ self.kernel_size = kernel_size
70
+ self.p_dropout = p_dropout
71
+ self.proximal_bias = proximal_bias
72
+ self.proximal_init = proximal_init
73
+
74
+ self.drop = nn.Dropout(p_dropout)
75
+ self.self_attn_layers = nn.ModuleList()
76
+ self.norm_layers_0 = nn.ModuleList()
77
+ self.encdec_attn_layers = nn.ModuleList()
78
+ self.norm_layers_1 = nn.ModuleList()
79
+ self.ffn_layers = nn.ModuleList()
80
+ self.norm_layers_2 = nn.ModuleList()
81
+ for i in range(self.n_layers):
82
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
83
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
84
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
85
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
86
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
87
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
88
+
89
+ def forward(self, x, x_mask, h, h_mask):
90
+ """
91
+ x: decoder input
92
+ h: encoder output
93
+ """
94
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
95
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
96
+ x = x * x_mask
97
+ for i in range(self.n_layers):
98
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
99
+ y = self.drop(y)
100
+ x = self.norm_layers_0[i](x + y)
101
+
102
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
103
+ y = self.drop(y)
104
+ x = self.norm_layers_1[i](x + y)
105
+
106
+ y = self.ffn_layers[i](x, x_mask)
107
+ y = self.drop(y)
108
+ x = self.norm_layers_2[i](x + y)
109
+ x = x * x_mask
110
+ return x
111
+
112
+
113
+ class MultiHeadAttention(nn.Module):
114
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
115
+ super().__init__()
116
+ assert channels % n_heads == 0
117
+
118
+ self.channels = channels
119
+ self.out_channels = out_channels
120
+ self.n_heads = n_heads
121
+ self.p_dropout = p_dropout
122
+ self.window_size = window_size
123
+ self.heads_share = heads_share
124
+ self.block_length = block_length
125
+ self.proximal_bias = proximal_bias
126
+ self.proximal_init = proximal_init
127
+ self.attn = None
128
+
129
+ self.k_channels = channels // n_heads
130
+ self.conv_q = nn.Conv1d(channels, channels, 1)
131
+ self.conv_k = nn.Conv1d(channels, channels, 1)
132
+ self.conv_v = nn.Conv1d(channels, channels, 1)
133
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
134
+ self.drop = nn.Dropout(p_dropout)
135
+
136
+ if window_size is not None:
137
+ n_heads_rel = 1 if heads_share else n_heads
138
+ rel_stddev = self.k_channels**-0.5
139
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
140
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
141
+
142
+ nn.init.xavier_uniform_(self.conv_q.weight)
143
+ nn.init.xavier_uniform_(self.conv_k.weight)
144
+ nn.init.xavier_uniform_(self.conv_v.weight)
145
+ if proximal_init:
146
+ with torch.no_grad():
147
+ self.conv_k.weight.copy_(self.conv_q.weight)
148
+ self.conv_k.bias.copy_(self.conv_q.bias)
149
+
150
+ def forward(self, x, c, attn_mask=None):
151
+ q = self.conv_q(x)
152
+ k = self.conv_k(c)
153
+ v = self.conv_v(c)
154
+
155
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
156
+
157
+ x = self.conv_o(x)
158
+ return x
159
+
160
+ def attention(self, query, key, value, mask=None):
161
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
162
+ b, d, t_s, t_t = (*key.size(), query.size(2))
163
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
164
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
165
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
166
+
167
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
168
+ if self.window_size is not None:
169
+ assert t_s == t_t, "Relative attention is only available for self-attention."
170
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
171
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
172
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
173
+ scores = scores + scores_local
174
+ if self.proximal_bias:
175
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
176
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
177
+ if mask is not None:
178
+ scores = scores.masked_fill(mask == 0, -1e4)
179
+ if self.block_length is not None:
180
+ assert t_s == t_t, "Local attention is only available for self-attention."
181
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
182
+ scores = scores.masked_fill(block_mask == 0, -1e4)
183
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
184
+ p_attn = self.drop(p_attn)
185
+ output = torch.matmul(p_attn, value)
186
+ if self.window_size is not None:
187
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
188
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
189
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
190
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
191
+ return output, p_attn
192
+
193
+ def _matmul_with_relative_values(self, x, y):
194
+ """
195
+ x: [b, h, l, m]
196
+ y: [h or 1, m, d]
197
+ ret: [b, h, l, d]
198
+ """
199
+ ret = torch.matmul(x, y.unsqueeze(0))
200
+ return ret
201
+
202
+ def _matmul_with_relative_keys(self, x, y):
203
+ """
204
+ x: [b, h, l, d]
205
+ y: [h or 1, m, d]
206
+ ret: [b, h, l, m]
207
+ """
208
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
209
+ return ret
210
+
211
+ def _get_relative_embeddings(self, relative_embeddings, length):
212
+ max_relative_position = 2 * self.window_size + 1
213
+ # Pad first before slice to avoid using cond ops.
214
+ pad_length = max(length - (self.window_size + 1), 0)
215
+ slice_start_position = max((self.window_size + 1) - length, 0)
216
+ slice_end_position = slice_start_position + 2 * length - 1
217
+ if pad_length > 0:
218
+ padded_relative_embeddings = F.pad(
219
+ relative_embeddings,
220
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
221
+ else:
222
+ padded_relative_embeddings = relative_embeddings
223
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
224
+ return used_relative_embeddings
225
+
226
+ def _relative_position_to_absolute_position(self, x):
227
+ """
228
+ x: [b, h, l, 2*l-1]
229
+ ret: [b, h, l, l]
230
+ """
231
+ batch, heads, length, _ = x.size()
232
+ # Concat columns of pad to shift from relative to absolute indexing.
233
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
234
+
235
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
236
+ x_flat = x.view([batch, heads, length * 2 * length])
237
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]))
238
+
239
+ # Reshape and slice out the padded elements.
240
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
241
+ return x_final
242
+
243
+ def _absolute_position_to_relative_position(self, x):
244
+ """
245
+ x: [b, h, l, l]
246
+ ret: [b, h, l, 2*l-1]
247
+ """
248
+ batch, heads, length, _ = x.size()
249
+ # padd along column
250
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]))
251
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
252
+ # add 0's in the beginning that will skew the elements after reshape
253
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
254
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
255
+ return x_final
256
+
257
+ def _attention_bias_proximal(self, length):
258
+ """Bias for self-attention to encourage attention to close positions.
259
+ Args:
260
+ length: an integer scalar.
261
+ Returns:
262
+ a Tensor with shape [1, 1, length, length]
263
+ """
264
+ r = torch.arange(length, dtype=torch.float32)
265
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
266
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
267
+
268
+
269
+ class FFN(nn.Module):
270
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
271
+ super().__init__()
272
+ self.in_channels = in_channels
273
+ self.out_channels = out_channels
274
+ self.filter_channels = filter_channels
275
+ self.kernel_size = kernel_size
276
+ self.p_dropout = p_dropout
277
+ self.activation = activation
278
+ self.causal = causal
279
+
280
+ if causal:
281
+ self.padding = self._causal_padding
282
+ else:
283
+ self.padding = self._same_padding
284
+
285
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
286
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
287
+ self.drop = nn.Dropout(p_dropout)
288
+
289
+ def forward(self, x, x_mask):
290
+ x = self.conv_1(self.padding(x * x_mask))
291
+ if self.activation == "gelu":
292
+ x = x * torch.sigmoid(1.702 * x)
293
+ else:
294
+ x = torch.relu(x)
295
+ x = self.drop(x)
296
+ x = self.conv_2(self.padding(x * x_mask))
297
+ return x * x_mask
298
+
299
+ def _causal_padding(self, x):
300
+ if self.kernel_size == 1:
301
+ return x
302
+ pad_l = self.kernel_size - 1
303
+ pad_r = 0
304
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
305
+ x = F.pad(x, commons.convert_pad_shape(padding))
306
+ return x
307
+
308
+ def _same_padding(self, x):
309
+ if self.kernel_size == 1:
310
+ return x
311
+ pad_l = (self.kernel_size - 1) // 2
312
+ pad_r = self.kernel_size // 2
313
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
314
+ x = F.pad(x, commons.convert_pad_shape(padding))
315
+ return x
316
+
317
+
318
+ import torch.nn as nn
319
+ from torch.nn.utils import remove_weight_norm, weight_norm
320
+
321
+
322
+ class Depthwise_Separable_Conv1D(nn.Module):
323
+ def __init__(
324
+ self,
325
+ in_channels,
326
+ out_channels,
327
+ kernel_size,
328
+ stride=1,
329
+ padding=0,
330
+ dilation=1,
331
+ bias=True,
332
+ padding_mode='zeros', # TODO: refine this type
333
+ device=None,
334
+ dtype=None
335
+ ):
336
+ super().__init__()
337
+ self.depth_conv = nn.Conv1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,
338
+ groups=in_channels, stride=stride, padding=padding, dilation=dilation, bias=bias,
339
+ padding_mode=padding_mode, device=device, dtype=dtype)
340
+ self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias,
341
+ device=device, dtype=dtype)
342
+
343
+ def forward(self, input):
344
+ return self.point_conv(self.depth_conv(input))
345
+
346
+ def weight_norm(self):
347
+ self.depth_conv = weight_norm(self.depth_conv, name='weight')
348
+ self.point_conv = weight_norm(self.point_conv, name='weight')
349
+
350
+ def remove_weight_norm(self):
351
+ self.depth_conv = remove_weight_norm(self.depth_conv, name='weight')
352
+ self.point_conv = remove_weight_norm(self.point_conv, name='weight')
353
+
354
+
355
+ class Depthwise_Separable_TransposeConv1D(nn.Module):
356
+ def __init__(
357
+ self,
358
+ in_channels,
359
+ out_channels,
360
+ kernel_size,
361
+ stride=1,
362
+ padding=0,
363
+ output_padding=0,
364
+ bias=True,
365
+ dilation=1,
366
+ padding_mode='zeros', # TODO: refine this type
367
+ device=None,
368
+ dtype=None
369
+ ):
370
+ super().__init__()
371
+ self.depth_conv = nn.ConvTranspose1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,
372
+ groups=in_channels, stride=stride, output_padding=output_padding,
373
+ padding=padding, dilation=dilation, bias=bias, padding_mode=padding_mode,
374
+ device=device, dtype=dtype)
375
+ self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias,
376
+ device=device, dtype=dtype)
377
+
378
+ def forward(self, input):
379
+ return self.point_conv(self.depth_conv(input))
380
+
381
+ def weight_norm(self):
382
+ self.depth_conv = weight_norm(self.depth_conv, name='weight')
383
+ self.point_conv = weight_norm(self.point_conv, name='weight')
384
+
385
+ def remove_weight_norm(self):
386
+ remove_weight_norm(self.depth_conv, name='weight')
387
+ remove_weight_norm(self.point_conv, name='weight')
388
+
389
+
390
+ def weight_norm_modules(module, name='weight', dim=0):
391
+ if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
392
+ module.weight_norm()
393
+ return module
394
+ else:
395
+ return weight_norm(module, name, dim)
396
+
397
+
398
+ def remove_weight_norm_modules(module, name='weight'):
399
+ if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
400
+ module.remove_weight_norm()
401
+ else:
402
+ remove_weight_norm(module, name)
403
+
404
+
405
+ class FFT(nn.Module):
406
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0.,
407
+ proximal_bias=False, proximal_init=True, isflow = False, **kwargs):
408
+ super().__init__()
409
+ self.hidden_channels = hidden_channels
410
+ self.filter_channels = filter_channels
411
+ self.n_heads = n_heads
412
+ self.n_layers = n_layers
413
+ self.kernel_size = kernel_size
414
+ self.p_dropout = p_dropout
415
+ self.proximal_bias = proximal_bias
416
+ self.proximal_init = proximal_init
417
+ if isflow:
418
+ cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2*hidden_channels*n_layers, 1)
419
+ self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
420
+ self.cond_layer = weight_norm_modules(cond_layer, name='weight')
421
+ self.gin_channels = kwargs["gin_channels"]
422
+ self.drop = nn.Dropout(p_dropout)
423
+ self.self_attn_layers = nn.ModuleList()
424
+ self.norm_layers_0 = nn.ModuleList()
425
+ self.ffn_layers = nn.ModuleList()
426
+ self.norm_layers_1 = nn.ModuleList()
427
+ for i in range(self.n_layers):
428
+ self.self_attn_layers.append(
429
+ MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias,
430
+ proximal_init=proximal_init))
431
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
432
+ self.ffn_layers.append(
433
+ FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
434
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
435
+
436
+ def forward(self, x, x_mask, g = None):
437
+ """
438
+ x: decoder input
439
+ h: encoder output
440
+ """
441
+ if g is not None:
442
+ g = self.cond_layer(g)
443
+
444
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
445
+ x = x * x_mask
446
+ for i in range(self.n_layers):
447
+ if g is not None:
448
+ x = self.cond_pre(x)
449
+ cond_offset = i * 2 * self.hidden_channels
450
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
451
+ x = commons.fused_add_tanh_sigmoid_multiply(
452
+ x,
453
+ g_l,
454
+ torch.IntTensor([self.hidden_channels]))
455
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
456
+ y = self.drop(y)
457
+ x = self.norm_layers_0[i](x + y)
458
+
459
+ y = self.ffn_layers[i](x, x_mask)
460
+ y = self.drop(y)
461
+ x = self.norm_layers_1[i](x + y)
462
+ x = x * x_mask
463
+ return x
464
+
465
+
466
+
467
+ class TransformerCouplingLayer(nn.Module):
468
+ def __init__(self,
469
+ channels,
470
+ hidden_channels,
471
+ kernel_size,
472
+ n_layers,
473
+ n_heads,
474
+ p_dropout=0,
475
+ filter_channels=0,
476
+ mean_only=False,
477
+ wn_sharing_parameter=None,
478
+ gin_channels = 0
479
+ ):
480
+ assert channels % 2 == 0, "channels should be divisible by 2"
481
+ super().__init__()
482
+ self.channels = channels
483
+ self.hidden_channels = hidden_channels
484
+ self.kernel_size = kernel_size
485
+ self.n_layers = n_layers
486
+ self.half_channels = channels // 2
487
+ self.mean_only = mean_only
488
+
489
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
490
+ self.enc = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter
491
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
492
+ self.post.weight.data.zero_()
493
+ self.post.bias.data.zero_()
494
+
495
+ def forward(self, x, x_mask, g=None, reverse=False):
496
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
497
+ h = self.pre(x0) * x_mask
498
+ h = self.enc(h, x_mask, g=g)
499
+ stats = self.post(h) * x_mask
500
+ if not self.mean_only:
501
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
502
+ else:
503
+ m = stats
504
+ logs = torch.zeros_like(m)
505
+
506
+ if not reverse:
507
+ x1 = m + x1 * torch.exp(logs) * x_mask
508
+ x = torch.cat([x0, x1], 1)
509
+ logdet = torch.sum(logs, [1,2])
510
+ return x, logdet
511
+ else:
512
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
513
+ x = torch.cat([x0, x1], 1)
514
+ return x
module/commons.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ def init_weights(m, mean=0.0, std=0.01):
9
+ classname = m.__class__.__name__
10
+ if classname.find("Conv") != -1:
11
+ m.weight.data.normal_(mean, std)
12
+
13
+
14
+ def get_padding(kernel_size, dilation=1):
15
+ return int((kernel_size*dilation - dilation)/2)
16
+
17
+
18
+ def convert_pad_shape(pad_shape):
19
+ l = pad_shape[::-1]
20
+ pad_shape = [item for sublist in l for item in sublist]
21
+ return pad_shape
22
+
23
+
24
+ def intersperse(lst, item):
25
+ result = [item] * (len(lst) * 2 + 1)
26
+ result[1::2] = lst
27
+ return result
28
+
29
+
30
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
31
+ """KL(P||Q)"""
32
+ kl = (logs_q - logs_p) - 0.5
33
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
34
+ return kl
35
+
36
+
37
+ def rand_gumbel(shape):
38
+ """Sample from the Gumbel distribution, protect from overflows."""
39
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
40
+ return -torch.log(-torch.log(uniform_samples))
41
+
42
+
43
+ def rand_gumbel_like(x):
44
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
45
+ return g
46
+
47
+
48
+ def slice_segments(x, ids_str, segment_size=4):
49
+ ret = torch.zeros_like(x[:, :, :segment_size])
50
+ for i in range(x.size(0)):
51
+ idx_str = ids_str[i]
52
+ idx_end = idx_str + segment_size
53
+ ret[i] = x[i, :, idx_str:idx_end]
54
+ return ret
55
+
56
+
57
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
58
+ b, d, t = x.size()
59
+ if x_lengths is None:
60
+ x_lengths = t
61
+ ids_str_max = x_lengths - segment_size + 1
62
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
63
+ ret = slice_segments(x, ids_str, segment_size)
64
+ return ret, ids_str
65
+
66
+
67
+ def get_timing_signal_1d(
68
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
69
+ position = torch.arange(length, dtype=torch.float)
70
+ num_timescales = channels // 2
71
+ log_timescale_increment = (
72
+ math.log(float(max_timescale) / float(min_timescale)) /
73
+ (num_timescales - 1))
74
+ inv_timescales = min_timescale * torch.exp(
75
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
76
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
77
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
78
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
79
+ signal = signal.view(1, channels, length)
80
+ return signal
81
+
82
+
83
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
84
+ b, channels, length = x.size()
85
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
86
+ return x + signal.to(dtype=x.dtype, device=x.device)
87
+
88
+
89
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
90
+ b, channels, length = x.size()
91
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
92
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
93
+
94
+
95
+ def subsequent_mask(length):
96
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
97
+ return mask
98
+
99
+
100
+ @torch.jit.script
101
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
102
+ n_channels_int = n_channels[0]
103
+ in_act = input_a + input_b
104
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
105
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
106
+ acts = t_act * s_act
107
+ return acts
108
+
109
+
110
+ def convert_pad_shape(pad_shape):
111
+ l = pad_shape[::-1]
112
+ pad_shape = [item for sublist in l for item in sublist]
113
+ return pad_shape
114
+
115
+
116
+ def shift_1d(x):
117
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
118
+ return x
119
+
120
+
121
+ def sequence_mask(length, max_length=None):
122
+ if max_length is None:
123
+ max_length = length.max()
124
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
125
+ return x.unsqueeze(0) < length.unsqueeze(1)
126
+
127
+
128
+ def generate_path(duration, mask):
129
+ """
130
+ duration: [b, 1, t_x]
131
+ mask: [b, 1, t_y, t_x]
132
+ """
133
+ device = duration.device
134
+
135
+ b, _, t_y, t_x = mask.shape
136
+ cum_duration = torch.cumsum(duration, -1)
137
+
138
+ cum_duration_flat = cum_duration.view(b * t_x)
139
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
140
+ path = path.view(b, t_x, t_y)
141
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
142
+ path = path.unsqueeze(1).transpose(2,3) * mask
143
+ return path
144
+
145
+
146
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
147
+ if isinstance(parameters, torch.Tensor):
148
+ parameters = [parameters]
149
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
150
+ norm_type = float(norm_type)
151
+ if clip_value is not None:
152
+ clip_value = float(clip_value)
153
+
154
+ total_norm = 0
155
+ for p in parameters:
156
+ param_norm = p.grad.data.norm(norm_type)
157
+ total_norm += param_norm.item() ** norm_type
158
+ if clip_value is not None:
159
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
160
+ total_norm = total_norm ** (1. / norm_type)
161
+ return total_norm
162
+
163
+
164
+ def squeeze(x, x_mask=None, n_sqz=2):
165
+ b, c, t = x.size()
166
+
167
+ t = (t // n_sqz) * n_sqz
168
+ x = x[:, :, :t]
169
+ x_sqz = x.view(b, c, t // n_sqz, n_sqz)
170
+ x_sqz = x_sqz.permute(0, 3, 1, 2).contiguous().view(b, c * n_sqz, t // n_sqz)
171
+
172
+ if x_mask is not None:
173
+ x_mask = x_mask[:, :, n_sqz - 1::n_sqz]
174
+ else:
175
+ x_mask = torch.ones(b, 1, t // n_sqz).to(device=x.device, dtype=x.dtype)
176
+ return x_sqz * x_mask, x_mask
177
+
178
+
179
+ def unsqueeze(x, x_mask=None, n_sqz=2):
180
+ b, c, t = x.size()
181
+
182
+ x_unsqz = x.view(b, n_sqz, c // n_sqz, t)
183
+ x_unsqz = x_unsqz.permute(0, 2, 3, 1).contiguous().view(b, c // n_sqz, t * n_sqz)
184
+
185
+ if x_mask is not None:
186
+ x_mask = x_mask.unsqueeze(-1).repeat(1, 1, 1, n_sqz).view(b, 1, t * n_sqz)
187
+ else:
188
+ x_mask = torch.ones(b, 1, t * n_sqz).to(device=x.device, dtype=x.dtype)
189
+ return x_unsqz * x_mask, x_mask
module/core_vq.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ #
7
+ # This implementation is inspired from
8
+ # https://github.com/lucidrains/vector-quantize-pytorch
9
+ # which is released under MIT License. Hereafter, the original license:
10
+ # MIT License
11
+ #
12
+ # Copyright (c) 2020 Phil Wang
13
+ #
14
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ # of this software and associated documentation files (the "Software"), to deal
16
+ # in the Software without restriction, including without limitation the rights
17
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ # copies of the Software, and to permit persons to whom the Software is
19
+ # furnished to do so, subject to the following conditions:
20
+ #
21
+ # The above copyright notice and this permission notice shall be included in all
22
+ # copies or substantial portions of the Software.
23
+ #
24
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ # SOFTWARE.
31
+
32
+ """Core vector quantization implementation."""
33
+ import typing as tp
34
+
35
+ from einops import rearrange, repeat
36
+ import torch
37
+ from torch import nn
38
+ import torch.nn.functional as F
39
+ from tqdm import tqdm
40
+
41
+
42
+ def default(val: tp.Any, d: tp.Any) -> tp.Any:
43
+ return val if val is not None else d
44
+
45
+
46
+ def ema_inplace(moving_avg, new, decay: float):
47
+ moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
48
+
49
+
50
+ def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
51
+ return (x + epsilon) / (x.sum() + n_categories * epsilon)
52
+
53
+
54
+ def uniform_init(*shape: int):
55
+ t = torch.empty(shape)
56
+ nn.init.kaiming_uniform_(t)
57
+ return t
58
+
59
+
60
+ def sample_vectors(samples, num: int):
61
+ num_samples, device = samples.shape[0], samples.device
62
+
63
+ if num_samples >= num:
64
+ indices = torch.randperm(num_samples, device=device)[:num]
65
+ else:
66
+ indices = torch.randint(0, num_samples, (num,), device=device)
67
+
68
+ return samples[indices]
69
+
70
+
71
+ def kmeans(samples, num_clusters: int, num_iters: int = 10):
72
+ dim, dtype = samples.shape[-1], samples.dtype
73
+ max_kmeans_samples = 500
74
+ samples = samples[:max_kmeans_samples, :]
75
+ means = sample_vectors(samples, num_clusters)
76
+
77
+ print("kmeans start ... ")
78
+ for _ in tqdm(range(num_iters)):
79
+ diffs = rearrange(samples, "n d -> n () d") - rearrange(
80
+ means, "c d -> () c d"
81
+ )
82
+ dists = -(diffs ** 2).sum(dim=-1)
83
+
84
+ buckets = dists.max(dim=-1).indices
85
+ bins = torch.bincount(buckets, minlength=num_clusters)
86
+ zero_mask = bins == 0
87
+ bins_min_clamped = bins.masked_fill(zero_mask, 1)
88
+
89
+ new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
90
+ new_means.scatter_add_(0, repeat(buckets, "n -> n d", d=dim), samples)
91
+ new_means = new_means / bins_min_clamped[..., None]
92
+
93
+ means = torch.where(zero_mask[..., None], means, new_means)
94
+
95
+ return means, bins
96
+
97
+
98
+ class EuclideanCodebook(nn.Module):
99
+ """Codebook with Euclidean distance.
100
+ Args:
101
+ dim (int): Dimension.
102
+ codebook_size (int): Codebook size.
103
+ kmeans_init (bool): Whether to use k-means to initialize the codebooks.
104
+ If set to true, run the k-means algorithm on the first training batch and use
105
+ the learned centroids as initialization.
106
+ kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
107
+ decay (float): Decay for exponential moving average over the codebooks.
108
+ epsilon (float): Epsilon value for numerical stability.
109
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
110
+ that have an exponential moving average cluster size less than the specified threshold with
111
+ randomly selected vector from the current batch.
112
+ """
113
+ def __init__(
114
+ self,
115
+ dim: int,
116
+ codebook_size: int,
117
+ kmeans_init: int = False,
118
+ kmeans_iters: int = 10,
119
+ decay: float = 0.99,
120
+ epsilon: float = 1e-5,
121
+ threshold_ema_dead_code: int = 2,
122
+ ):
123
+ super().__init__()
124
+ self.decay = decay
125
+ init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros
126
+ embed = init_fn(codebook_size, dim)
127
+
128
+ self.codebook_size = codebook_size
129
+
130
+ self.kmeans_iters = kmeans_iters
131
+ self.epsilon = epsilon
132
+ self.threshold_ema_dead_code = threshold_ema_dead_code
133
+
134
+ self.register_buffer("inited", torch.Tensor([not kmeans_init]))
135
+ self.register_buffer("cluster_size", torch.zeros(codebook_size))
136
+ self.register_buffer("embed", embed)
137
+ self.register_buffer("embed_avg", embed.clone())
138
+
139
+ @torch.jit.ignore
140
+ def init_embed_(self, data):
141
+ if self.inited:
142
+ return
143
+
144
+ embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)
145
+ self.embed.data.copy_(embed)
146
+ self.embed_avg.data.copy_(embed.clone())
147
+ self.cluster_size.data.copy_(cluster_size)
148
+ self.inited.data.copy_(torch.Tensor([True]))
149
+ # Make sure all buffers across workers are in sync after initialization
150
+ #broadcast_tensors(self.buffers())
151
+
152
+ def replace_(self, samples, mask):
153
+ modified_codebook = torch.where(
154
+ mask[..., None], sample_vectors(samples, self.codebook_size), self.embed
155
+ )
156
+ self.embed.data.copy_(modified_codebook)
157
+
158
+ def expire_codes_(self, batch_samples):
159
+ if self.threshold_ema_dead_code == 0:
160
+ return
161
+
162
+ expired_codes = self.cluster_size < self.threshold_ema_dead_code
163
+ if not torch.any(expired_codes):
164
+ return
165
+
166
+ batch_samples = rearrange(batch_samples, "... d -> (...) d")
167
+ self.replace_(batch_samples, mask=expired_codes)
168
+ #broadcast_tensors(self.buffers())
169
+
170
+ def preprocess(self, x):
171
+ x = rearrange(x, "... d -> (...) d")
172
+ return x
173
+
174
+ def quantize(self, x):
175
+ embed = self.embed.t()
176
+ dist = -(
177
+ x.pow(2).sum(1, keepdim=True)
178
+ - 2 * x @ embed
179
+ + embed.pow(2).sum(0, keepdim=True)
180
+ )
181
+ embed_ind = dist.max(dim=-1).indices
182
+ return embed_ind
183
+
184
+ def postprocess_emb(self, embed_ind, shape):
185
+ return embed_ind.view(*shape[:-1])
186
+
187
+ def dequantize(self, embed_ind):
188
+ quantize = F.embedding(embed_ind, self.embed)
189
+ return quantize
190
+
191
+ def encode(self, x):
192
+ shape = x.shape
193
+ # pre-process
194
+ x = self.preprocess(x)
195
+ # quantize
196
+ embed_ind = self.quantize(x)
197
+ # post-process
198
+ embed_ind = self.postprocess_emb(embed_ind, shape)
199
+ return embed_ind
200
+
201
+ def decode(self, embed_ind):
202
+ quantize = self.dequantize(embed_ind)
203
+ return quantize
204
+
205
+ def forward(self, x):
206
+ shape, dtype = x.shape, x.dtype
207
+ x = self.preprocess(x)
208
+
209
+ self.init_embed_(x)
210
+
211
+ embed_ind = self.quantize(x)
212
+ embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)
213
+ embed_ind = self.postprocess_emb(embed_ind, shape)
214
+ quantize = self.dequantize(embed_ind)
215
+
216
+ if self.training:
217
+ # We do the expiry of code at that point as buffers are in sync
218
+ # and all the workers will take the same decision.
219
+ self.expire_codes_(x)
220
+ ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)
221
+ embed_sum = x.t() @ embed_onehot
222
+ ema_inplace(self.embed_avg, embed_sum.t(), self.decay)
223
+ cluster_size = (
224
+ laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon)
225
+ * self.cluster_size.sum()
226
+ )
227
+ embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
228
+ self.embed.data.copy_(embed_normalized)
229
+
230
+ return quantize, embed_ind
231
+
232
+
233
+ class VectorQuantization(nn.Module):
234
+ """Vector quantization implementation.
235
+ Currently supports only euclidean distance.
236
+ Args:
237
+ dim (int): Dimension
238
+ codebook_size (int): Codebook size
239
+ codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
240
+ decay (float): Decay for exponential moving average over the codebooks.
241
+ epsilon (float): Epsilon value for numerical stability.
242
+ kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
243
+ kmeans_iters (int): Number of iterations used for kmeans initialization.
244
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
245
+ that have an exponential moving average cluster size less than the specified threshold with
246
+ randomly selected vector from the current batch.
247
+ commitment_weight (float): Weight for commitment loss.
248
+ """
249
+ def __init__(
250
+ self,
251
+ dim: int,
252
+ codebook_size: int,
253
+ codebook_dim: tp.Optional[int] = None,
254
+ decay: float = 0.99,
255
+ epsilon: float = 1e-5,
256
+ kmeans_init: bool = True,
257
+ kmeans_iters: int = 50,
258
+ threshold_ema_dead_code: int = 2,
259
+ commitment_weight: float = 1.,
260
+ ):
261
+ super().__init__()
262
+ _codebook_dim: int = default(codebook_dim, dim)
263
+
264
+ requires_projection = _codebook_dim != dim
265
+ self.project_in = (nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity())
266
+ self.project_out = (nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity())
267
+
268
+ self.epsilon = epsilon
269
+ self.commitment_weight = commitment_weight
270
+
271
+ self._codebook = EuclideanCodebook(dim=_codebook_dim, codebook_size=codebook_size,
272
+ kmeans_init=kmeans_init, kmeans_iters=kmeans_iters,
273
+ decay=decay, epsilon=epsilon,
274
+ threshold_ema_dead_code=threshold_ema_dead_code)
275
+ self.codebook_size = codebook_size
276
+
277
+ @property
278
+ def codebook(self):
279
+ return self._codebook.embed
280
+
281
+ def encode(self, x):
282
+ x = rearrange(x, "b d n -> b n d")
283
+ x = self.project_in(x)
284
+ embed_in = self._codebook.encode(x)
285
+ return embed_in
286
+
287
+ def decode(self, embed_ind):
288
+ quantize = self._codebook.decode(embed_ind)
289
+ quantize = self.project_out(quantize)
290
+ quantize = rearrange(quantize, "b n d -> b d n")
291
+ return quantize
292
+
293
+ def forward(self, x):
294
+ device = x.device
295
+ x = rearrange(x, "b d n -> b n d")
296
+ x = self.project_in(x)
297
+
298
+ quantize, embed_ind = self._codebook(x)
299
+
300
+ if self.training:
301
+ quantize = x + (quantize - x).detach()
302
+
303
+ loss = torch.tensor([0.0], device=device, requires_grad=self.training)
304
+
305
+ if self.training:
306
+ if self.commitment_weight > 0:
307
+ commit_loss = F.mse_loss(quantize.detach(), x)
308
+ loss = loss + commit_loss * self.commitment_weight
309
+
310
+ quantize = self.project_out(quantize)
311
+ quantize = rearrange(quantize, "b n d -> b d n")
312
+ return quantize, embed_ind, loss
313
+
314
+
315
+ class ResidualVectorQuantization(nn.Module):
316
+ """Residual vector quantization implementation.
317
+ Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
318
+ """
319
+ def __init__(self, *, num_quantizers, **kwargs):
320
+ super().__init__()
321
+ self.layers = nn.ModuleList(
322
+ [VectorQuantization(**kwargs) for _ in range(num_quantizers)]
323
+ )
324
+
325
+ def forward(self, x, n_q: tp.Optional[int] = None, layers: tp.Optional[list] = None):
326
+ quantized_out = 0.0
327
+ residual = x
328
+
329
+ all_losses = []
330
+ all_indices = []
331
+ out_quantized = []
332
+
333
+ n_q = n_q or len(self.layers)
334
+
335
+ for i, layer in enumerate(self.layers[:n_q]):
336
+ quantized, indices, loss = layer(residual)
337
+ residual = residual - quantized
338
+ quantized_out = quantized_out + quantized
339
+
340
+ all_indices.append(indices)
341
+ all_losses.append(loss)
342
+ if layers and i in layers:
343
+ out_quantized.append(quantized)
344
+
345
+ out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
346
+ return quantized_out, out_indices, out_losses, out_quantized
347
+
348
+ def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None, st: tp.Optional[int]= None) -> torch.Tensor:
349
+ residual = x
350
+ all_indices = []
351
+ n_q = n_q or len(self.layers)
352
+ st = st or 0
353
+ for layer in self.layers[st:n_q]:
354
+ indices = layer.encode(residual)
355
+ quantized = layer.decode(indices)
356
+ residual = residual - quantized
357
+ all_indices.append(indices)
358
+ out_indices = torch.stack(all_indices)
359
+ return out_indices
360
+
361
+ def decode(self, q_indices: torch.Tensor, st: int=0) -> torch.Tensor:
362
+ quantized_out = torch.tensor(0.0, device=q_indices.device)
363
+ for i, indices in enumerate(q_indices):
364
+ layer = self.layers[st + i]
365
+ quantized = layer.decode(indices)
366
+ quantized_out = quantized_out + quantized
367
+ return quantized_out
module/data_utils.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time,logging
2
+ import os
3
+ import random,traceback
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+ from tqdm import tqdm
8
+
9
+ from module import commons
10
+ from module.mel_processing import spectrogram_torch
11
+ from text import cleaned_text_to_sequence
12
+ from utils import load_wav_to_torch, load_filepaths_and_text
13
+ import torch.nn.functional as F
14
+ from functools import lru_cache
15
+ import torch
16
+ import requests
17
+ from scipy.io import wavfile
18
+ from io import BytesIO
19
+ # from config import exp_dir
20
+ from my_utils import load_audio
21
+
22
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
23
+ """
24
+ 1) loads audio, speaker_id, text pairs
25
+ 2) normalizes text and converts them to sequences of integers
26
+ 3) computes spectrograms from audio files.
27
+ """
28
+
29
+ def __init__(self, hparams, val=False):
30
+ exp_dir=hparams.exp_dir
31
+ self.path2="%s/2-name2text.txt"%exp_dir
32
+ self.path4="%s/4-cnhubert"%exp_dir
33
+ self.path5="%s/5-wav32k"%exp_dir
34
+ assert os.path.exists(self.path2)
35
+ assert os.path.exists(self.path4)
36
+ assert os.path.exists(self.path5)
37
+ names4=set([name[:-3]for name in list(os.listdir(self.path4))])#去除.pt后缀
38
+ names5=set(os.listdir(self.path5))
39
+ self.phoneme_data={}
40
+ with open(self.path2,"r",encoding="utf8")as f:
41
+ lines=f.read().strip("\n").split("\n")
42
+
43
+ for line in lines:
44
+ tmp=line.split("\t")
45
+ if(len(tmp)!=4):continue
46
+ self.phoneme_data[tmp[0]]=[tmp[1]]
47
+
48
+ self.audiopaths_sid_text=list(set(self.phoneme_data)&names4&names5)
49
+ tmp=self.audiopaths_sid_text
50
+ leng=len(tmp)
51
+ min_num=100
52
+ if(leng<min_num):
53
+ self.audiopaths_sid_text=[]
54
+ for _ in range(max(2, int(min_num / leng))):
55
+ self.audiopaths_sid_text += tmp
56
+ self.max_wav_value = hparams.max_wav_value
57
+ self.sampling_rate = hparams.sampling_rate
58
+ self.filter_length = hparams.filter_length
59
+ self.hop_length = hparams.hop_length
60
+ self.win_length = hparams.win_length
61
+ self.sampling_rate = hparams.sampling_rate
62
+ self.val = val
63
+
64
+ random.seed(1234)
65
+ random.shuffle(self.audiopaths_sid_text)
66
+
67
+ print("phoneme_data_len:", len(self.phoneme_data.keys()))
68
+ print("wav_data_len:", len(self.audiopaths_sid_text))
69
+
70
+ audiopaths_sid_text_new = []
71
+ lengths = []
72
+ skipped_phone = 0
73
+ skipped_dur = 0
74
+ for audiopath in tqdm(self.audiopaths_sid_text):
75
+ try:
76
+ phoneme = self.phoneme_data[audiopath][0]
77
+ phoneme = phoneme.split(' ')
78
+ phoneme_ids = cleaned_text_to_sequence(phoneme)
79
+ except Exception:
80
+ print(f"{audiopath} not in self.phoneme_data !")
81
+ skipped_phone += 1
82
+ continue
83
+ size=os.path.getsize("%s/%s"%(self.path5,audiopath))
84
+ duration = size / self.sampling_rate / 2
85
+ if (54 > duration > 0.6 or self.val):
86
+ audiopaths_sid_text_new.append([audiopath, phoneme_ids])
87
+ lengths.append(size // (2 * self.hop_length))
88
+ else:
89
+ skipped_dur += 1
90
+ continue
91
+ print("skipped_phone: ", skipped_phone, ", skipped_dur: ", skipped_dur)
92
+ print("total left: ", len(audiopaths_sid_text_new))
93
+ assert len(audiopaths_sid_text_new)>1#至少能凑够batch size,这里todo
94
+ self.audiopaths_sid_text = audiopaths_sid_text_new
95
+ self.lengths = lengths
96
+
97
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
98
+ audiopath, phoneme_ids = audiopath_sid_text
99
+ text = torch.FloatTensor(phoneme_ids)
100
+ try:
101
+ spec, wav = self.get_audio("%s/%s"%(self.path5,audiopath))
102
+ with torch.no_grad():
103
+ ssl = torch.load("%s/%s.pt"%(self.path4,audiopath),map_location="cpu")
104
+ if(ssl.shape[-1]!=spec.shape[-1]):
105
+ typee=ssl.dtype
106
+ ssl=F.pad(ssl.float(),(0,1),mode="replicate").to(typee)
107
+ ssl.requires_grad=False
108
+ except:
109
+ traceback.print_exc()
110
+ spec = torch.zeros(1025, 100)
111
+ wav = torch.zeros(1, 100*self.hop_length)
112
+ ssl=torch.zeros(1,768,100)
113
+ text=text[-1:]
114
+ print("load audio or ssl error!!!!!!", audiopath)
115
+ # print(ssl.requires_grad,spec.requires_grad,wav.requires_grad,text.requires_grad)
116
+ return (ssl, spec, wav, text)
117
+
118
+ def get_audio(self, filename):
119
+ audio_array = load_audio(filename,self.sampling_rate)#load_audio的方法是已经归一化到-1~1之间的,不用再/32768
120
+ # print(filename,audio_array.max(),audio_array.min(),audio_array.mean())
121
+ audio=torch.FloatTensor(audio_array)#/32768
122
+ audio_norm = audio
123
+ audio_norm = audio_norm.unsqueeze(0)
124
+ spec = spectrogram_torch(audio_norm, self.filter_length,self.sampling_rate, self.hop_length, self.win_length,center=False)
125
+ spec = torch.squeeze(spec, 0)
126
+ return spec, audio_norm
127
+
128
+ def get_sid(self, sid):
129
+ sid = torch.LongTensor([int(sid)])
130
+ return sid
131
+
132
+ def __getitem__(self, index):
133
+ # with torch.no_grad():
134
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
135
+
136
+ def __len__(self):
137
+ return len(self.audiopaths_sid_text)
138
+
139
+ def random_slice(self, ssl, wav, mel):
140
+ assert abs(ssl.shape[-1]- wav.shape[-1]//self.hop_length) < 3, ("first", ssl.shape, wav.shape)
141
+
142
+ len_mel = mel.shape[1]
143
+ if self.val:
144
+ reference_mel = mel[:, :len_mel//3]
145
+ return reference_mel, ssl, wav, mel
146
+ dir = random.randint(0, 1)
147
+ sep_point = random.randint(int(len_mel//3), int(len_mel//3*2))
148
+
149
+ if dir == 0:
150
+ reference_mel = mel[:, :sep_point]
151
+ ssl = ssl[:, :, sep_point:]
152
+ wav2 = wav[:, sep_point*self.hop_length:]
153
+ mel = mel[:, sep_point:]
154
+ else:
155
+ reference_mel = mel[:, sep_point:]
156
+ ssl = ssl[:, :, :sep_point]
157
+ wav2 = wav[:, :sep_point*self.hop_length]
158
+ mel = mel[:, :sep_point]
159
+
160
+ assert abs(ssl.shape[-1]- wav2.shape[-1]//self.hop_length) < 3, (ssl.shape, wav.shape,wav2.shape, mel.shape, sep_point,self.hop_length, sep_point*self.hop_length, dir)
161
+ return reference_mel, ssl, wav2, mel
162
+
163
+
164
+ class TextAudioSpeakerCollate():
165
+ """ Zero-pads model inputs and targets
166
+ """
167
+
168
+ def __init__(self, return_ids=False):
169
+ self.return_ids = return_ids
170
+
171
+ def __call__(self, batch):
172
+ """Collate's training batch from normalized text, audio and speaker identities
173
+ PARAMS
174
+ ------
175
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
176
+ """
177
+ # Right zero-pad all one-hot text sequences to max input length
178
+ _, ids_sorted_decreasing = torch.sort(
179
+ torch.LongTensor([x[1].size(1) for x in batch]),
180
+ dim=0, descending=True)
181
+
182
+ max_ssl_len = max([x[0].size(2) for x in batch])
183
+ max_ssl_len = int(2 * ((max_ssl_len // 2) + 1))
184
+ max_spec_len = max([x[1].size(1) for x in batch])
185
+ max_spec_len = int(2 * ((max_spec_len // 2) + 1))
186
+ max_wav_len = max([x[2].size(1) for x in batch])
187
+ max_text_len = max([x[3].size(0) for x in batch])
188
+
189
+ ssl_lengths = torch.LongTensor(len(batch))
190
+ spec_lengths = torch.LongTensor(len(batch))
191
+ wav_lengths = torch.LongTensor(len(batch))
192
+ text_lengths = torch.LongTensor(len(batch))
193
+
194
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
195
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
196
+ ssl_padded = torch.FloatTensor(len(batch), batch[0][0].size(1), max_ssl_len)
197
+ text_padded = torch.LongTensor(len(batch), max_text_len)
198
+
199
+ spec_padded.zero_()
200
+ wav_padded.zero_()
201
+ ssl_padded.zero_()
202
+ text_padded.zero_()
203
+
204
+ for i in range(len(ids_sorted_decreasing)):
205
+ row = batch[ids_sorted_decreasing[i]]
206
+
207
+ ssl = row[0]
208
+ ssl_padded[i, :, :ssl.size(2)] = ssl[0, :, :]
209
+ ssl_lengths[i] = ssl.size(2)
210
+
211
+ spec = row[1]
212
+ spec_padded[i, :, :spec.size(1)] = spec
213
+ spec_lengths[i] = spec.size(1)
214
+
215
+ wav = row[2]
216
+ wav_padded[i, :, :wav.size(1)] = wav
217
+ wav_lengths[i] = wav.size(1)
218
+
219
+ text = row[3]
220
+ text_padded[i, :text.size(0)] = text
221
+ text_lengths[i] = text.size(0)
222
+
223
+
224
+ return ssl_padded, ssl_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, text_padded, text_lengths
225
+
226
+
227
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
228
+ """
229
+ Maintain similar input lengths in a batch.
230
+ Length groups are specified by boundaries.
231
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
232
+
233
+ It removes samples which are not included in the boundaries.
234
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
235
+ """
236
+
237
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
238
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
239
+ self.lengths = dataset.lengths
240
+ # print(233333333333333,self.lengths,dir(dataset))
241
+ self.batch_size = batch_size
242
+ self.boundaries = boundaries
243
+
244
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
245
+ self.total_size = sum(self.num_samples_per_bucket)
246
+ self.num_samples = self.total_size // self.num_replicas
247
+
248
+ def _create_buckets(self):
249
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
250
+ for i in range(len(self.lengths)):
251
+ length = self.lengths[i]
252
+ idx_bucket = self._bisect(length)
253
+ if idx_bucket != -1:
254
+ buckets[idx_bucket].append(i)
255
+
256
+ for i in range(len(buckets) - 1, 0, -1):
257
+ # for i in range(len(buckets) - 1, -1, -1):
258
+ if len(buckets[i]) == 0:
259
+ buckets.pop(i)
260
+ self.boundaries.pop(i + 1)
261
+
262
+ num_samples_per_bucket = []
263
+ for i in range(len(buckets)):
264
+ len_bucket = len(buckets[i])
265
+ total_batch_size = self.num_replicas * self.batch_size
266
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
267
+ num_samples_per_bucket.append(len_bucket + rem)
268
+ return buckets, num_samples_per_bucket
269
+
270
+ def __iter__(self):
271
+ # deterministically shuffle based on epoch
272
+ g = torch.Generator()
273
+ g.manual_seed(self.epoch)
274
+
275
+ indices = []
276
+ if self.shuffle:
277
+ for bucket in self.buckets:
278
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
279
+ else:
280
+ for bucket in self.buckets:
281
+ indices.append(list(range(len(bucket))))
282
+
283
+ batches = []
284
+ for i in range(len(self.buckets)):
285
+ bucket = self.buckets[i]
286
+ len_bucket = len(bucket)
287
+ ids_bucket = indices[i]
288
+ num_samples_bucket = self.num_samples_per_bucket[i]
289
+
290
+ # add extra samples to make it evenly divisible
291
+ rem = num_samples_bucket - len_bucket
292
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
293
+
294
+ # subsample
295
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
296
+
297
+ # batching
298
+ for j in range(len(ids_bucket) // self.batch_size):
299
+ batch = [bucket[idx] for idx in ids_bucket[j * self.batch_size:(j + 1) * self.batch_size]]
300
+ batches.append(batch)
301
+
302
+ if self.shuffle:
303
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
304
+ batches = [batches[i] for i in batch_ids]
305
+ self.batches = batches
306
+
307
+ assert len(self.batches) * self.batch_size == self.num_samples
308
+ return iter(self.batches)
309
+
310
+ def _bisect(self, x, lo=0, hi=None):
311
+ if hi is None:
312
+ hi = len(self.boundaries) - 1
313
+
314
+ if hi > lo:
315
+ mid = (hi + lo) // 2
316
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
317
+ return mid
318
+ elif x <= self.boundaries[mid]:
319
+ return self._bisect(x, lo, mid)
320
+ else:
321
+ return self._bisect(x, mid + 1, hi)
322
+ else:
323
+ return -1
324
+
325
+ def __len__(self):
326
+ return self.num_samples // self.batch_size
module/losses.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
62
+
63
+ def mle_loss(z, m, logs, logdet, mask):
64
+ l = torch.sum(logs) + 0.5 * torch.sum(torch.exp(-2 * logs) * ((z - m)**2)) # neg normal likelihood w/o the constant term
65
+ l = l - torch.sum(logdet) # log jacobian determinant
66
+ l = l / torch.sum(torch.ones_like(z) * mask) # averaging across batch, channel and time axes
67
+ l = l + 0.5 * math.log(2 * math.pi) # add the remaining constant term
68
+ return l
module/mel_processing.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.data
8
+ import numpy as np
9
+ import librosa
10
+ import librosa.util as librosa_util
11
+ from librosa.util import normalize, pad_center, tiny
12
+ from scipy.signal import get_window
13
+ from scipy.io.wavfile import read
14
+ from librosa.filters import mel as librosa_mel_fn
15
+
16
+ MAX_WAV_VALUE = 32768.0
17
+
18
+
19
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
20
+ """
21
+ PARAMS
22
+ ------
23
+ C: compression factor
24
+ """
25
+ return torch.log(torch.clamp(x, min=clip_val) * C)
26
+
27
+
28
+ def dynamic_range_decompression_torch(x, C=1):
29
+ """
30
+ PARAMS
31
+ ------
32
+ C: compression factor used to compress
33
+ """
34
+ return torch.exp(x) / C
35
+
36
+
37
+ def spectral_normalize_torch(magnitudes):
38
+ output = dynamic_range_compression_torch(magnitudes)
39
+ return output
40
+
41
+
42
+ def spectral_de_normalize_torch(magnitudes):
43
+ output = dynamic_range_decompression_torch(magnitudes)
44
+ return output
45
+
46
+
47
+ mel_basis = {}
48
+ hann_window = {}
49
+
50
+
51
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
52
+ if torch.min(y) < -1.:
53
+ print('min value is ', torch.min(y))
54
+ if torch.max(y) > 1.:
55
+ print('max value is ', torch.max(y))
56
+
57
+ global hann_window
58
+ dtype_device = str(y.dtype) + '_' + str(y.device)
59
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
60
+ if wnsize_dtype_device not in hann_window:
61
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
62
+
63
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
64
+ y = y.squeeze(1)
65
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
66
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
67
+
68
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
69
+ return spec
70
+
71
+
72
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
73
+ global mel_basis
74
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
75
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
76
+ if fmax_dtype_device not in mel_basis:
77
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
78
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
79
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
80
+ spec = spectral_normalize_torch(spec)
81
+ return spec
82
+
83
+
84
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
85
+ if torch.min(y) < -1.:
86
+ print('min value is ', torch.min(y))
87
+ if torch.max(y) > 1.:
88
+ print('max value is ', torch.max(y))
89
+
90
+ global mel_basis, hann_window
91
+ dtype_device = str(y.dtype) + '_' + str(y.device)
92
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
93
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
94
+ if fmax_dtype_device not in mel_basis:
95
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
96
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
97
+ if wnsize_dtype_device not in hann_window:
98
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
99
+
100
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
101
+ y = y.squeeze(1)
102
+
103
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
104
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
105
+
106
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
107
+
108
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
109
+ spec = spectral_normalize_torch(spec)
110
+
111
+ return spec
module/models.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from module import commons
8
+ from module import modules
9
+ from module import attentions
10
+
11
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
12
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
13
+ from module.commons import init_weights, get_padding
14
+ from module.mrte_model import MRTE
15
+ from module.quantize import ResidualVectorQuantizer
16
+ from text import symbols
17
+ from torch.cuda.amp import autocast
18
+
19
+ class StochasticDurationPredictor(nn.Module):
20
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
21
+ super().__init__()
22
+ filter_channels = in_channels # it needs to be removed from future version.
23
+ self.in_channels = in_channels
24
+ self.filter_channels = filter_channels
25
+ self.kernel_size = kernel_size
26
+ self.p_dropout = p_dropout
27
+ self.n_flows = n_flows
28
+ self.gin_channels = gin_channels
29
+
30
+ self.log_flow = modules.Log()
31
+ self.flows = nn.ModuleList()
32
+ self.flows.append(modules.ElementwiseAffine(2))
33
+ for i in range(n_flows):
34
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
35
+ self.flows.append(modules.Flip())
36
+
37
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
38
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
39
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
40
+ self.post_flows = nn.ModuleList()
41
+ self.post_flows.append(modules.ElementwiseAffine(2))
42
+ for i in range(4):
43
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
44
+ self.post_flows.append(modules.Flip())
45
+
46
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
47
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
48
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
49
+ if gin_channels != 0:
50
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
51
+
52
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
53
+ x = torch.detach(x)
54
+ x = self.pre(x)
55
+ if g is not None:
56
+ g = torch.detach(g)
57
+ x = x + self.cond(g)
58
+ x = self.convs(x, x_mask)
59
+ x = self.proj(x) * x_mask
60
+
61
+ if not reverse:
62
+ flows = self.flows
63
+ assert w is not None
64
+
65
+ logdet_tot_q = 0
66
+ h_w = self.post_pre(w)
67
+ h_w = self.post_convs(h_w, x_mask)
68
+ h_w = self.post_proj(h_w) * x_mask
69
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
70
+ z_q = e_q
71
+ for flow in self.post_flows:
72
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
73
+ logdet_tot_q += logdet_q
74
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
75
+ u = torch.sigmoid(z_u) * x_mask
76
+ z0 = (w - u) * x_mask
77
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
78
+ logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q
79
+
80
+ logdet_tot = 0
81
+ z0, logdet = self.log_flow(z0, x_mask)
82
+ logdet_tot += logdet
83
+ z = torch.cat([z0, z1], 1)
84
+ for flow in flows:
85
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
86
+ logdet_tot = logdet_tot + logdet
87
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot
88
+ return nll + logq # [b]
89
+ else:
90
+ flows = list(reversed(self.flows))
91
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
92
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
93
+ for flow in flows:
94
+ z = flow(z, x_mask, g=x, reverse=reverse)
95
+ z0, z1 = torch.split(z, [1, 1], 1)
96
+ logw = z0
97
+ return logw
98
+
99
+
100
+ class DurationPredictor(nn.Module):
101
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
102
+ super().__init__()
103
+
104
+ self.in_channels = in_channels
105
+ self.filter_channels = filter_channels
106
+ self.kernel_size = kernel_size
107
+ self.p_dropout = p_dropout
108
+ self.gin_channels = gin_channels
109
+
110
+ self.drop = nn.Dropout(p_dropout)
111
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
112
+ self.norm_1 = modules.LayerNorm(filter_channels)
113
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
114
+ self.norm_2 = modules.LayerNorm(filter_channels)
115
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
116
+
117
+ if gin_channels != 0:
118
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
119
+
120
+ def forward(self, x, x_mask, g=None):
121
+ x = torch.detach(x)
122
+ if g is not None:
123
+ g = torch.detach(g)
124
+ x = x + self.cond(g)
125
+ x = self.conv_1(x * x_mask)
126
+ x = torch.relu(x)
127
+ x = self.norm_1(x)
128
+ x = self.drop(x)
129
+ x = self.conv_2(x * x_mask)
130
+ x = torch.relu(x)
131
+ x = self.norm_2(x)
132
+ x = self.drop(x)
133
+ x = self.proj(x * x_mask)
134
+ return x * x_mask
135
+
136
+
137
+ class TextEncoder(nn.Module):
138
+ def __init__(self,
139
+ out_channels,
140
+ hidden_channels,
141
+ filter_channels,
142
+ n_heads,
143
+ n_layers,
144
+ kernel_size,
145
+ p_dropout,
146
+ latent_channels=192):
147
+ super().__init__()
148
+ self.out_channels = out_channels
149
+ self.hidden_channels = hidden_channels
150
+ self.filter_channels = filter_channels
151
+ self.n_heads = n_heads
152
+ self.n_layers = n_layers
153
+ self.kernel_size = kernel_size
154
+ self.p_dropout = p_dropout
155
+ self.latent_channels = latent_channels
156
+
157
+ self.ssl_proj = nn.Conv1d(768, hidden_channels, 1)
158
+
159
+ self.encoder_ssl = attentions.Encoder(
160
+ hidden_channels,
161
+ filter_channels,
162
+ n_heads,
163
+ n_layers//2,
164
+ kernel_size,
165
+ p_dropout)
166
+
167
+ self.encoder_text = attentions.Encoder(
168
+ hidden_channels,
169
+ filter_channels,
170
+ n_heads,
171
+ n_layers,
172
+ kernel_size,
173
+ p_dropout)
174
+ self.text_embedding = nn.Embedding(len(symbols), hidden_channels)
175
+
176
+ self.mrte = MRTE()
177
+
178
+ self.encoder2 = attentions.Encoder(
179
+ hidden_channels,
180
+ filter_channels,
181
+ n_heads,
182
+ n_layers//2,
183
+ kernel_size,
184
+ p_dropout)
185
+
186
+
187
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
188
+
189
+ def forward(self, y, y_lengths, text, text_lengths, ge, test=None):
190
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
191
+
192
+ y = self.ssl_proj(y * y_mask) * y_mask
193
+ y = self.encoder_ssl(y * y_mask, y_mask)
194
+
195
+ text_mask = torch.unsqueeze(commons.sequence_mask(text_lengths, text.size(1)), 1).to(y.dtype)
196
+ if test == 1 :
197
+ text[:, :] = 0
198
+ text = self.text_embedding(text).transpose(1, 2)
199
+ text = self.encoder_text(text * text_mask, text_mask)
200
+ y = self.mrte(y, y_mask, text, text_mask, ge)
201
+
202
+ y = self.encoder2(y * y_mask, y_mask)
203
+
204
+ stats = self.proj(y) * y_mask
205
+ m, logs = torch.split(stats, self.out_channels, dim=1)
206
+ return y, m, logs, y_mask
207
+
208
+ def extract_latent(self, x):
209
+ x = self.ssl_proj(x)
210
+ quantized, codes, commit_loss, quantized_list = self.quantizer(x)
211
+ return codes.transpose(0,1)
212
+ def decode_latent(self, codes, y_mask, refer,refer_mask, ge):
213
+
214
+ quantized = self.quantizer.decode(codes)
215
+
216
+ y = self.vq_proj(quantized) * y_mask
217
+ y = self.encoder_ssl(y * y_mask, y_mask)
218
+
219
+ y = self.mrte(y, y_mask, refer, refer_mask, ge)
220
+
221
+ y = self.encoder2(y * y_mask, y_mask)
222
+
223
+ stats = self.proj(y) * y_mask
224
+ m, logs = torch.split(stats, self.out_channels, dim=1)
225
+ return y, m, logs, y_mask, quantized
226
+
227
+ class ResidualCouplingBlock(nn.Module):
228
+ def __init__(self,
229
+ channels,
230
+ hidden_channels,
231
+ kernel_size,
232
+ dilation_rate,
233
+ n_layers,
234
+ n_flows=4,
235
+ gin_channels=0):
236
+ super().__init__()
237
+ self.channels = channels
238
+ self.hidden_channels = hidden_channels
239
+ self.kernel_size = kernel_size
240
+ self.dilation_rate = dilation_rate
241
+ self.n_layers = n_layers
242
+ self.n_flows = n_flows
243
+ self.gin_channels = gin_channels
244
+
245
+ self.flows = nn.ModuleList()
246
+ for i in range(n_flows):
247
+ self.flows.append(
248
+ modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
249
+ gin_channels=gin_channels, mean_only=True))
250
+ self.flows.append(modules.Flip())
251
+
252
+ def forward(self, x, x_mask, g=None, reverse=False):
253
+ if not reverse:
254
+ for flow in self.flows:
255
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
256
+ else:
257
+ for flow in reversed(self.flows):
258
+ x = flow(x, x_mask, g=g, reverse=reverse)
259
+ return x
260
+
261
+
262
+ class PosteriorEncoder(nn.Module):
263
+ def __init__(self,
264
+ in_channels,
265
+ out_channels,
266
+ hidden_channels,
267
+ kernel_size,
268
+ dilation_rate,
269
+ n_layers,
270
+ gin_channels=0):
271
+ super().__init__()
272
+ self.in_channels = in_channels
273
+ self.out_channels = out_channels
274
+ self.hidden_channels = hidden_channels
275
+ self.kernel_size = kernel_size
276
+ self.dilation_rate = dilation_rate
277
+ self.n_layers = n_layers
278
+ self.gin_channels = gin_channels
279
+
280
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
281
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
282
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
283
+
284
+ def forward(self, x, x_lengths, g=None):
285
+ if(g!=None):
286
+ g = g.detach()
287
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
288
+ x = self.pre(x) * x_mask
289
+ x = self.enc(x, x_mask, g=g)
290
+ stats = self.proj(x) * x_mask
291
+ m, logs = torch.split(stats, self.out_channels, dim=1)
292
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
293
+ return z, m, logs, x_mask
294
+
295
+
296
+ class WNEncoder(nn.Module):
297
+ def __init__(self,
298
+ in_channels,
299
+ out_channels,
300
+ hidden_channels,
301
+ kernel_size,
302
+ dilation_rate,
303
+ n_layers,
304
+ gin_channels=0):
305
+ super().__init__()
306
+ self.in_channels = in_channels
307
+ self.out_channels = out_channels
308
+ self.hidden_channels = hidden_channels
309
+ self.kernel_size = kernel_size
310
+ self.dilation_rate = dilation_rate
311
+ self.n_layers = n_layers
312
+ self.gin_channels = gin_channels
313
+
314
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
315
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
316
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
317
+ self.norm = modules.LayerNorm(out_channels)
318
+ def forward(self, x, x_lengths, g=None):
319
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
320
+ x = self.pre(x) * x_mask
321
+ x = self.enc(x, x_mask, g=g)
322
+ out = self.proj(x) * x_mask
323
+ out = self.norm(out)
324
+ return out
325
+
326
+
327
+ class Generator(torch.nn.Module):
328
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
329
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
330
+ super(Generator, self).__init__()
331
+ self.num_kernels = len(resblock_kernel_sizes)
332
+ self.num_upsamples = len(upsample_rates)
333
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
334
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
335
+
336
+ self.ups = nn.ModuleList()
337
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
338
+ self.ups.append(weight_norm(
339
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
340
+ k, u, padding=(k - u) // 2)))
341
+
342
+ self.resblocks = nn.ModuleList()
343
+ for i in range(len(self.ups)):
344
+ ch = upsample_initial_channel // (2 ** (i + 1))
345
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
346
+ self.resblocks.append(resblock(ch, k, d))
347
+
348
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
349
+ self.ups.apply(init_weights)
350
+
351
+ if gin_channels != 0:
352
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
353
+
354
+ def forward(self, x, g=None):
355
+ x = self.conv_pre(x)
356
+ if g is not None:
357
+ x = x + self.cond(g)
358
+
359
+ for i in range(self.num_upsamples):
360
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
361
+ x = self.ups[i](x)
362
+ xs = None
363
+ for j in range(self.num_kernels):
364
+ if xs is None:
365
+ xs = self.resblocks[i * self.num_kernels + j](x)
366
+ else:
367
+ xs += self.resblocks[i * self.num_kernels + j](x)
368
+ x = xs / self.num_kernels
369
+ x = F.leaky_relu(x)
370
+ x = self.conv_post(x)
371
+ x = torch.tanh(x)
372
+
373
+ return x
374
+
375
+ def remove_weight_norm(self):
376
+ print('Removing weight norm...')
377
+ for l in self.ups:
378
+ remove_weight_norm(l)
379
+ for l in self.resblocks:
380
+ l.remove_weight_norm()
381
+
382
+
383
+ class DiscriminatorP(torch.nn.Module):
384
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
385
+ super(DiscriminatorP, self).__init__()
386
+ self.period = period
387
+ self.use_spectral_norm = use_spectral_norm
388
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
389
+ self.convs = nn.ModuleList([
390
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
391
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
392
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
393
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
394
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
395
+ ])
396
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
397
+
398
+ def forward(self, x):
399
+ fmap = []
400
+
401
+ # 1d to 2d
402
+ b, c, t = x.shape
403
+ if t % self.period != 0: # pad first
404
+ n_pad = self.period - (t % self.period)
405
+ x = F.pad(x, (0, n_pad), "reflect")
406
+ t = t + n_pad
407
+ x = x.view(b, c, t // self.period, self.period)
408
+
409
+ for l in self.convs:
410
+ x = l(x)
411
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
412
+ fmap.append(x)
413
+ x = self.conv_post(x)
414
+ fmap.append(x)
415
+ x = torch.flatten(x, 1, -1)
416
+
417
+ return x, fmap
418
+
419
+
420
+ class DiscriminatorS(torch.nn.Module):
421
+ def __init__(self, use_spectral_norm=False):
422
+ super(DiscriminatorS, self).__init__()
423
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
424
+ self.convs = nn.ModuleList([
425
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
426
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
427
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
428
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
429
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
430
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
431
+ ])
432
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
433
+
434
+ def forward(self, x):
435
+ fmap = []
436
+
437
+ for l in self.convs:
438
+ x = l(x)
439
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
440
+ fmap.append(x)
441
+ x = self.conv_post(x)
442
+ fmap.append(x)
443
+ x = torch.flatten(x, 1, -1)
444
+
445
+ return x, fmap
446
+
447
+
448
+ class MultiPeriodDiscriminator(torch.nn.Module):
449
+ def __init__(self, use_spectral_norm=False):
450
+ super(MultiPeriodDiscriminator, self).__init__()
451
+ periods = [2, 3, 5, 7, 11]
452
+
453
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
454
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
455
+ self.discriminators = nn.ModuleList(discs)
456
+
457
+ def forward(self, y, y_hat):
458
+ y_d_rs = []
459
+ y_d_gs = []
460
+ fmap_rs = []
461
+ fmap_gs = []
462
+ for i, d in enumerate(self.discriminators):
463
+ y_d_r, fmap_r = d(y)
464
+ y_d_g, fmap_g = d(y_hat)
465
+ y_d_rs.append(y_d_r)
466
+ y_d_gs.append(y_d_g)
467
+ fmap_rs.append(fmap_r)
468
+ fmap_gs.append(fmap_g)
469
+
470
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
471
+
472
+ class ReferenceEncoder(nn.Module):
473
+ '''
474
+ inputs --- [N, Ty/r, n_mels*r] mels
475
+ outputs --- [N, ref_enc_gru_size]
476
+ '''
477
+
478
+ def __init__(self, spec_channels, gin_channels=0):
479
+
480
+ super().__init__()
481
+ self.spec_channels = spec_channels
482
+ ref_enc_filters = [32, 32, 64, 64, 128, 128]
483
+ K = len(ref_enc_filters)
484
+ filters = [1] + ref_enc_filters
485
+ convs = [weight_norm(nn.Conv2d(in_channels=filters[i],
486
+ out_channels=filters[i + 1],
487
+ kernel_size=(3, 3),
488
+ stride=(2, 2),
489
+ padding=(1, 1))) for i in range(K)]
490
+ self.convs = nn.ModuleList(convs)
491
+ # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
492
+
493
+ out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
494
+ self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels,
495
+ hidden_size=256 // 2,
496
+ batch_first=True)
497
+ self.proj = nn.Linear(128, gin_channels)
498
+
499
+ def forward(self, inputs):
500
+ N = inputs.size(0)
501
+ out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
502
+ for conv in self.convs:
503
+ out = conv(out)
504
+ # out = wn(out)
505
+ out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
506
+
507
+ out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
508
+ T = out.size(1)
509
+ N = out.size(0)
510
+ out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
511
+
512
+ self.gru.flatten_parameters()
513
+ memory, out = self.gru(out) # out --- [1, N, 128]
514
+
515
+ return self.proj(out.squeeze(0)).unsqueeze(-1)
516
+
517
+ def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
518
+ for i in range(n_convs):
519
+ L = (L - kernel_size + 2 * pad) // stride + 1
520
+ return L
521
+
522
+
523
+ class Quantizer_module(torch.nn.Module):
524
+ def __init__(self, n_e, e_dim):
525
+ super(Quantizer_module, self).__init__()
526
+ self.embedding = nn.Embedding(n_e, e_dim)
527
+ self.embedding.weight.data.uniform_(-1.0 / n_e, 1.0 / n_e)
528
+
529
+ def forward(self, x):
530
+ d = torch.sum(x ** 2, 1, keepdim=True) + torch.sum(self.embedding.weight ** 2, 1) - 2 * torch.matmul(x, self.embedding.weight.T)
531
+ min_indicies = torch.argmin(d, 1)
532
+ z_q = self.embedding(min_indicies)
533
+ return z_q, min_indicies
534
+
535
+ class Quantizer(torch.nn.Module):
536
+ def __init__(self, embed_dim=512, n_code_groups=4, n_codes=160):
537
+ super(Quantizer, self).__init__()
538
+ assert embed_dim % n_code_groups == 0
539
+ self.quantizer_modules = nn.ModuleList([
540
+ Quantizer_module(n_codes, embed_dim // n_code_groups) for _ in range(n_code_groups)
541
+ ])
542
+ self.n_code_groups = n_code_groups
543
+ self.embed_dim = embed_dim
544
+
545
+ def forward(self, xin):
546
+ #B, C, T
547
+ B, C, T = xin.shape
548
+ xin = xin.transpose(1, 2)
549
+ x = xin.reshape(-1, self.embed_dim)
550
+ x = torch.split(x, self.embed_dim // self.n_code_groups, dim=-1)
551
+ min_indicies = []
552
+ z_q = []
553
+ for _x, m in zip(x, self.quantizer_modules):
554
+ _z_q, _min_indicies = m(_x)
555
+ z_q.append(_z_q)
556
+ min_indicies.append(_min_indicies) #B * T,
557
+ z_q = torch.cat(z_q, -1).reshape(xin.shape)
558
+ loss = 0.25 * torch.mean((z_q.detach() - xin) ** 2) + torch.mean((z_q - xin.detach()) ** 2)
559
+ z_q = xin + (z_q - xin).detach()
560
+ z_q = z_q.transpose(1, 2)
561
+ codes = torch.stack(min_indicies, -1).reshape(B, T, self.n_code_groups)
562
+ return z_q, loss, codes.transpose(1, 2)
563
+
564
+ def embed(self, x):
565
+ #idx: N, 4, T
566
+ x=x.transpose(1, 2)
567
+ x = torch.split(x, 1, 2)
568
+ ret = []
569
+ for q, embed in zip(x, self.quantizer_modules):
570
+ q = embed.embedding(q.squeeze(-1))
571
+ ret.append(q)
572
+ ret = torch.cat(ret, -1)
573
+ return ret.transpose(1, 2) #N, C, T
574
+
575
+
576
+ class CodePredictor(nn.Module):
577
+ def __init__(self,
578
+ hidden_channels,
579
+ filter_channels,
580
+ n_heads,
581
+ n_layers,
582
+ kernel_size,
583
+ p_dropout,
584
+ n_q=8,
585
+ dims=1024,
586
+ ssl_dim=768
587
+ ):
588
+ super().__init__()
589
+ self.hidden_channels = hidden_channels
590
+ self.filter_channels = filter_channels
591
+ self.n_heads = n_heads
592
+ self.n_layers = n_layers
593
+ self.kernel_size = kernel_size
594
+ self.p_dropout = p_dropout
595
+
596
+ self.vq_proj = nn.Conv1d(ssl_dim, hidden_channels, 1)
597
+ self.ref_enc = modules.MelStyleEncoder(ssl_dim, style_vector_dim=hidden_channels)
598
+
599
+ self.encoder = attentions.Encoder(
600
+ hidden_channels,
601
+ filter_channels,
602
+ n_heads,
603
+ n_layers,
604
+ kernel_size,
605
+ p_dropout)
606
+
607
+ self.out_proj = nn.Conv1d(hidden_channels, (n_q-1) * dims, 1)
608
+ self.n_q = n_q
609
+ self.dims = dims
610
+ def forward(self, x, x_mask, refer, codes, infer=False):
611
+ x = x.detach()
612
+ x = self.vq_proj(x * x_mask) * x_mask
613
+ g = self.ref_enc(refer, x_mask)
614
+ x = x + g
615
+ x = self.encoder(x * x_mask, x_mask)
616
+ x = self.out_proj(x * x_mask) * x_mask
617
+ logits = x.reshape(x.shape[0], self.n_q - 1, self.dims, x.shape[-1]).transpose(2, 3)
618
+ target = codes[1:].transpose(0, 1)
619
+ if not infer:
620
+ logits = logits.reshape(-1, self.dims)
621
+ target = target.reshape(-1)
622
+ loss = torch.nn.functional.cross_entropy(logits, target)
623
+ return loss
624
+ else:
625
+ _, top10_preds = torch.topk(logits, 10, dim=-1)
626
+ correct_top10 = torch.any(top10_preds == target.unsqueeze(-1), dim=-1)
627
+ top3_acc = 100 * torch.mean(correct_top10.float()).detach().cpu().item()
628
+
629
+ print('Top-10 Accuracy:', top3_acc, "%")
630
+
631
+ pred_codes = torch.argmax(logits, dim=-1)
632
+ acc = 100 * torch.mean((pred_codes == target).float()).detach().cpu().item()
633
+ print('Top-1 Accuracy:', acc, "%")
634
+
635
+ return pred_codes.transpose(0, 1)
636
+
637
+
638
+
639
+ class SynthesizerTrn(nn.Module):
640
+ """
641
+ Synthesizer for Training
642
+ """
643
+
644
+ def __init__(self,
645
+ spec_channels,
646
+ segment_size,
647
+ inter_channels,
648
+ hidden_channels,
649
+ filter_channels,
650
+ n_heads,
651
+ n_layers,
652
+ kernel_size,
653
+ p_dropout,
654
+ resblock,
655
+ resblock_kernel_sizes,
656
+ resblock_dilation_sizes,
657
+ upsample_rates,
658
+ upsample_initial_channel,
659
+ upsample_kernel_sizes,
660
+ n_speakers=0,
661
+ gin_channels=0,
662
+ use_sdp=True,
663
+ semantic_frame_rate=None,
664
+ freeze_quantizer=None,
665
+ **kwargs):
666
+
667
+ super().__init__()
668
+ self.spec_channels = spec_channels
669
+ self.inter_channels = inter_channels
670
+ self.hidden_channels = hidden_channels
671
+ self.filter_channels = filter_channels
672
+ self.n_heads = n_heads
673
+ self.n_layers = n_layers
674
+ self.kernel_size = kernel_size
675
+ self.p_dropout = p_dropout
676
+ self.resblock = resblock
677
+ self.resblock_kernel_sizes = resblock_kernel_sizes
678
+ self.resblock_dilation_sizes = resblock_dilation_sizes
679
+ self.upsample_rates = upsample_rates
680
+ self.upsample_initial_channel = upsample_initial_channel
681
+ self.upsample_kernel_sizes = upsample_kernel_sizes
682
+ self.segment_size = segment_size
683
+ self.n_speakers = n_speakers
684
+ self.gin_channels = gin_channels
685
+
686
+ self.use_sdp = use_sdp
687
+ self.enc_p = TextEncoder(
688
+ inter_channels,
689
+ hidden_channels,
690
+ filter_channels,
691
+ n_heads,
692
+ n_layers,
693
+ kernel_size,
694
+ p_dropout)
695
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
696
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
697
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
698
+ gin_channels=gin_channels)
699
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
700
+
701
+ self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)
702
+
703
+ ssl_dim = 768
704
+ assert semantic_frame_rate in ['25hz', "50hz"]
705
+ self.semantic_frame_rate = semantic_frame_rate
706
+ if semantic_frame_rate == '25hz':
707
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
708
+ else:
709
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
710
+
711
+ self.quantizer = ResidualVectorQuantizer(
712
+ dimension=ssl_dim,
713
+ n_q=1,
714
+ bins=1024
715
+ )
716
+ if freeze_quantizer:
717
+ self.ssl_proj.requires_grad_(False)
718
+ self.quantizer.requires_grad_(False)
719
+ # self.enc_p.text_embedding.requires_grad_(False)
720
+ # self.enc_p.encoder_text.requires_grad_(False)
721
+ # self.enc_p.mrte.requires_grad_(False)
722
+
723
+ def forward(self, ssl, y, y_lengths, text, text_lengths):
724
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
725
+ ge = self.ref_enc(y * y_mask, y_mask)
726
+
727
+ with autocast(enabled=False):
728
+ ssl = self.ssl_proj(ssl)
729
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl, layers=[0])
730
+
731
+ if self.semantic_frame_rate == '25hz':
732
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
733
+
734
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
735
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=ge)
736
+ z_p = self.flow(z, y_mask, g=ge)
737
+
738
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
739
+ o = self.dec(z_slice, g=ge)
740
+ return o, commit_loss, ids_slice, y_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), quantized
741
+
742
+ def infer(self, ssl, y, y_lengths, text, text_lengths, test=None, noise_scale=0.5):
743
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
744
+ ge = self.ref_enc(y * y_mask, y_mask)
745
+
746
+ ssl = self.ssl_proj(ssl)
747
+ quantized, codes, commit_loss, _ = self.quantizer(ssl, layers=[0])
748
+ if self.semantic_frame_rate == '25hz':
749
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
750
+
751
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge, test=test)
752
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
753
+
754
+ z = self.flow(z_p, y_mask, g=ge, reverse=True)
755
+
756
+ o = self.dec((z * y_mask)[:, :, :], g=ge)
757
+ return o,y_mask, (z, z_p, m_p, logs_p)
758
+
759
+
760
+ @torch.no_grad()
761
+ def decode(self, codes,text, refer, noise_scale=0.5):
762
+ refer_lengths = torch.LongTensor([refer.size(2)]).to(refer.device)
763
+ refer_mask = torch.unsqueeze(commons.sequence_mask(refer_lengths, refer.size(2)), 1).to(refer.dtype)
764
+ ge = self.ref_enc(refer * refer_mask, refer_mask)
765
+
766
+ y_lengths = torch.LongTensor([codes.size(2)*2]).to(codes.device)
767
+ text_lengths = torch.LongTensor([text.size(-1)]).to(text.device)
768
+
769
+ quantized = self.quantizer.decode(codes)
770
+ if self.semantic_frame_rate == '25hz':
771
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
772
+
773
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
774
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
775
+
776
+ z = self.flow(z_p, y_mask, g=ge, reverse=True)
777
+
778
+ o = self.dec((z * y_mask)[:, :, :], g=ge)
779
+ return o
780
+
781
+ def extract_latent(self, x):
782
+ ssl = self.ssl_proj(x)
783
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
784
+ return codes.transpose(0,1)
module/modules.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from torch.nn import Conv1d
8
+ from torch.nn.utils import weight_norm, remove_weight_norm
9
+
10
+ from module import commons
11
+ from module.commons import init_weights, get_padding
12
+ from module.transforms import piecewise_rational_quadratic_transform
13
+ import torch.distributions as D
14
+
15
+
16
+ LRELU_SLOPE = 0.1
17
+
18
+
19
+ class LayerNorm(nn.Module):
20
+ def __init__(self, channels, eps=1e-5):
21
+ super().__init__()
22
+ self.channels = channels
23
+ self.eps = eps
24
+
25
+ self.gamma = nn.Parameter(torch.ones(channels))
26
+ self.beta = nn.Parameter(torch.zeros(channels))
27
+
28
+ def forward(self, x):
29
+ x = x.transpose(1, -1)
30
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
31
+ return x.transpose(1, -1)
32
+
33
+
34
+ class ConvReluNorm(nn.Module):
35
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
36
+ super().__init__()
37
+ self.in_channels = in_channels
38
+ self.hidden_channels = hidden_channels
39
+ self.out_channels = out_channels
40
+ self.kernel_size = kernel_size
41
+ self.n_layers = n_layers
42
+ self.p_dropout = p_dropout
43
+ assert n_layers > 1, "Number of layers should be larger than 0."
44
+
45
+ self.conv_layers = nn.ModuleList()
46
+ self.norm_layers = nn.ModuleList()
47
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
48
+ self.norm_layers.append(LayerNorm(hidden_channels))
49
+ self.relu_drop = nn.Sequential(
50
+ nn.ReLU(),
51
+ nn.Dropout(p_dropout))
52
+ for _ in range(n_layers-1):
53
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
54
+ self.norm_layers.append(LayerNorm(hidden_channels))
55
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
56
+ self.proj.weight.data.zero_()
57
+ self.proj.bias.data.zero_()
58
+
59
+ def forward(self, x, x_mask):
60
+ x_org = x
61
+ for i in range(self.n_layers):
62
+ x = self.conv_layers[i](x * x_mask)
63
+ x = self.norm_layers[i](x)
64
+ x = self.relu_drop(x)
65
+ x = x_org + self.proj(x)
66
+ return x * x_mask
67
+
68
+
69
+ class DDSConv(nn.Module):
70
+ """
71
+ Dialted and Depth-Separable Convolution
72
+ """
73
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
74
+ super().__init__()
75
+ self.channels = channels
76
+ self.kernel_size = kernel_size
77
+ self.n_layers = n_layers
78
+ self.p_dropout = p_dropout
79
+
80
+ self.drop = nn.Dropout(p_dropout)
81
+ self.convs_sep = nn.ModuleList()
82
+ self.convs_1x1 = nn.ModuleList()
83
+ self.norms_1 = nn.ModuleList()
84
+ self.norms_2 = nn.ModuleList()
85
+ for i in range(n_layers):
86
+ dilation = kernel_size ** i
87
+ padding = (kernel_size * dilation - dilation) // 2
88
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
89
+ groups=channels, dilation=dilation, padding=padding
90
+ ))
91
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
92
+ self.norms_1.append(LayerNorm(channels))
93
+ self.norms_2.append(LayerNorm(channels))
94
+
95
+ def forward(self, x, x_mask, g=None):
96
+ if g is not None:
97
+ x = x + g
98
+ for i in range(self.n_layers):
99
+ y = self.convs_sep[i](x * x_mask)
100
+ y = self.norms_1[i](y)
101
+ y = F.gelu(y)
102
+ y = self.convs_1x1[i](y)
103
+ y = self.norms_2[i](y)
104
+ y = F.gelu(y)
105
+ y = self.drop(y)
106
+ x = x + y
107
+ return x * x_mask
108
+
109
+
110
+ class WN(torch.nn.Module):
111
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
112
+ super(WN, self).__init__()
113
+ assert(kernel_size % 2 == 1)
114
+ self.hidden_channels =hidden_channels
115
+ self.kernel_size = kernel_size,
116
+ self.dilation_rate = dilation_rate
117
+ self.n_layers = n_layers
118
+ self.gin_channels = gin_channels
119
+ self.p_dropout = p_dropout
120
+
121
+ self.in_layers = torch.nn.ModuleList()
122
+ self.res_skip_layers = torch.nn.ModuleList()
123
+ self.drop = nn.Dropout(p_dropout)
124
+
125
+ if gin_channels != 0:
126
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
127
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
128
+
129
+ for i in range(n_layers):
130
+ dilation = dilation_rate ** i
131
+ padding = int((kernel_size * dilation - dilation) / 2)
132
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
133
+ dilation=dilation, padding=padding)
134
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
135
+ self.in_layers.append(in_layer)
136
+
137
+ # last one is not necessary
138
+ if i < n_layers - 1:
139
+ res_skip_channels = 2 * hidden_channels
140
+ else:
141
+ res_skip_channels = hidden_channels
142
+
143
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
144
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
145
+ self.res_skip_layers.append(res_skip_layer)
146
+
147
+ def forward(self, x, x_mask, g=None, **kwargs):
148
+ output = torch.zeros_like(x)
149
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
150
+
151
+ if g is not None:
152
+ g = self.cond_layer(g)
153
+
154
+ for i in range(self.n_layers):
155
+ x_in = self.in_layers[i](x)
156
+ if g is not None:
157
+ cond_offset = i * 2 * self.hidden_channels
158
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
159
+ else:
160
+ g_l = torch.zeros_like(x_in)
161
+
162
+ acts = commons.fused_add_tanh_sigmoid_multiply(
163
+ x_in,
164
+ g_l,
165
+ n_channels_tensor)
166
+ acts = self.drop(acts)
167
+
168
+ res_skip_acts = self.res_skip_layers[i](acts)
169
+ if i < self.n_layers - 1:
170
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
171
+ x = (x + res_acts) * x_mask
172
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
173
+ else:
174
+ output = output + res_skip_acts
175
+ return output * x_mask
176
+
177
+ def remove_weight_norm(self):
178
+ if self.gin_channels != 0:
179
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
180
+ for l in self.in_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+ for l in self.res_skip_layers:
183
+ torch.nn.utils.remove_weight_norm(l)
184
+
185
+
186
+ class ResBlock1(torch.nn.Module):
187
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
188
+ super(ResBlock1, self).__init__()
189
+ self.convs1 = nn.ModuleList([
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
191
+ padding=get_padding(kernel_size, dilation[0]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
193
+ padding=get_padding(kernel_size, dilation[1]))),
194
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
195
+ padding=get_padding(kernel_size, dilation[2])))
196
+ ])
197
+ self.convs1.apply(init_weights)
198
+
199
+ self.convs2 = nn.ModuleList([
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1))),
204
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
205
+ padding=get_padding(kernel_size, 1)))
206
+ ])
207
+ self.convs2.apply(init_weights)
208
+
209
+ def forward(self, x, x_mask=None):
210
+ for c1, c2 in zip(self.convs1, self.convs2):
211
+ xt = F.leaky_relu(x, LRELU_SLOPE)
212
+ if x_mask is not None:
213
+ xt = xt * x_mask
214
+ xt = c1(xt)
215
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
216
+ if x_mask is not None:
217
+ xt = xt * x_mask
218
+ xt = c2(xt)
219
+ x = xt + x
220
+ if x_mask is not None:
221
+ x = x * x_mask
222
+ return x
223
+
224
+ def remove_weight_norm(self):
225
+ for l in self.convs1:
226
+ remove_weight_norm(l)
227
+ for l in self.convs2:
228
+ remove_weight_norm(l)
229
+
230
+
231
+ class ResBlock2(torch.nn.Module):
232
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
233
+ super(ResBlock2, self).__init__()
234
+ self.convs = nn.ModuleList([
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
236
+ padding=get_padding(kernel_size, dilation[0]))),
237
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
238
+ padding=get_padding(kernel_size, dilation[1])))
239
+ ])
240
+ self.convs.apply(init_weights)
241
+
242
+ def forward(self, x, x_mask=None):
243
+ for c in self.convs:
244
+ xt = F.leaky_relu(x, LRELU_SLOPE)
245
+ if x_mask is not None:
246
+ xt = xt * x_mask
247
+ xt = c(xt)
248
+ x = xt + x
249
+ if x_mask is not None:
250
+ x = x * x_mask
251
+ return x
252
+
253
+ def remove_weight_norm(self):
254
+ for l in self.convs:
255
+ remove_weight_norm(l)
256
+
257
+
258
+ class Log(nn.Module):
259
+ def forward(self, x, x_mask, reverse=False, **kwargs):
260
+ if not reverse:
261
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
262
+ logdet = torch.sum(-y, [1, 2])
263
+ return y, logdet
264
+ else:
265
+ x = torch.exp(x) * x_mask
266
+ return x
267
+
268
+
269
+ class Flip(nn.Module):
270
+ def forward(self, x, *args, reverse=False, **kwargs):
271
+ x = torch.flip(x, [1])
272
+ if not reverse:
273
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
274
+ return x, logdet
275
+ else:
276
+ return x
277
+
278
+
279
+ class ElementwiseAffine(nn.Module):
280
+ def __init__(self, channels):
281
+ super().__init__()
282
+ self.channels = channels
283
+ self.m = nn.Parameter(torch.zeros(channels,1))
284
+ self.logs = nn.Parameter(torch.zeros(channels,1))
285
+
286
+ def forward(self, x, x_mask, reverse=False, **kwargs):
287
+ if not reverse:
288
+ y = self.m + torch.exp(self.logs) * x
289
+ y = y * x_mask
290
+ logdet = torch.sum(self.logs * x_mask, [1,2])
291
+ return y, logdet
292
+ else:
293
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
294
+ return x
295
+
296
+
297
+ class ResidualCouplingLayer(nn.Module):
298
+ def __init__(self,
299
+ channels,
300
+ hidden_channels,
301
+ kernel_size,
302
+ dilation_rate,
303
+ n_layers,
304
+ p_dropout=0,
305
+ gin_channels=0,
306
+ mean_only=False):
307
+ assert channels % 2 == 0, "channels should be divisible by 2"
308
+ super().__init__()
309
+ self.channels = channels
310
+ self.hidden_channels = hidden_channels
311
+ self.kernel_size = kernel_size
312
+ self.dilation_rate = dilation_rate
313
+ self.n_layers = n_layers
314
+ self.half_channels = channels // 2
315
+ self.mean_only = mean_only
316
+
317
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
318
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
319
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
320
+ self.post.weight.data.zero_()
321
+ self.post.bias.data.zero_()
322
+
323
+ def forward(self, x, x_mask, g=None, reverse=False):
324
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
325
+ h = self.pre(x0) * x_mask
326
+ h = self.enc(h, x_mask, g=g)
327
+ stats = self.post(h) * x_mask
328
+ if not self.mean_only:
329
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
330
+ else:
331
+ m = stats
332
+ logs = torch.zeros_like(m)
333
+
334
+ if not reverse:
335
+ x1 = m + x1 * torch.exp(logs) * x_mask
336
+ x = torch.cat([x0, x1], 1)
337
+ logdet = torch.sum(logs, [1,2])
338
+ return x, logdet
339
+ else:
340
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
341
+ x = torch.cat([x0, x1], 1)
342
+ return x
343
+
344
+
345
+ class ConvFlow(nn.Module):
346
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
347
+ super().__init__()
348
+ self.in_channels = in_channels
349
+ self.filter_channels = filter_channels
350
+ self.kernel_size = kernel_size
351
+ self.n_layers = n_layers
352
+ self.num_bins = num_bins
353
+ self.tail_bound = tail_bound
354
+ self.half_channels = in_channels // 2
355
+
356
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
357
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
358
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
359
+ self.proj.weight.data.zero_()
360
+ self.proj.bias.data.zero_()
361
+
362
+ def forward(self, x, x_mask, g=None, reverse=False):
363
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
364
+ h = self.pre(x0)
365
+ h = self.convs(h, x_mask, g=g)
366
+ h = self.proj(h) * x_mask
367
+
368
+ b, c, t = x0.shape
369
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
370
+
371
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
372
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
373
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
374
+
375
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
376
+ unnormalized_widths,
377
+ unnormalized_heights,
378
+ unnormalized_derivatives,
379
+ inverse=reverse,
380
+ tails='linear',
381
+ tail_bound=self.tail_bound
382
+ )
383
+
384
+ x = torch.cat([x0, x1], 1) * x_mask
385
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
386
+ if not reverse:
387
+ return x, logdet
388
+ else:
389
+ return x
390
+
391
+
392
+
393
+ class LinearNorm(nn.Module):
394
+ def __init__(self,
395
+ in_channels,
396
+ out_channels,
397
+ bias=True,
398
+ spectral_norm=False,
399
+ ):
400
+ super(LinearNorm, self).__init__()
401
+ self.fc = nn.Linear(in_channels, out_channels, bias)
402
+
403
+ if spectral_norm:
404
+ self.fc = nn.utils.spectral_norm(self.fc)
405
+
406
+ def forward(self, input):
407
+ out = self.fc(input)
408
+ return out
409
+
410
+
411
+ class Mish(nn.Module):
412
+ def __init__(self):
413
+ super(Mish, self).__init__()
414
+
415
+ def forward(self, x):
416
+ return x * torch.tanh(F.softplus(x))
417
+
418
+
419
+ class Conv1dGLU(nn.Module):
420
+ '''
421
+ Conv1d + GLU(Gated Linear Unit) with residual connection.
422
+ For GLU refer to https://arxiv.org/abs/1612.08083 paper.
423
+ '''
424
+
425
+ def __init__(self, in_channels, out_channels, kernel_size, dropout):
426
+ super(Conv1dGLU, self).__init__()
427
+ self.out_channels = out_channels
428
+ self.conv1 = ConvNorm(in_channels, 2 * out_channels, kernel_size=kernel_size)
429
+ self.dropout = nn.Dropout(dropout)
430
+
431
+ def forward(self, x):
432
+ residual = x
433
+ x = self.conv1(x)
434
+ x1, x2 = torch.split(x, split_size_or_sections=self.out_channels, dim=1)
435
+ x = x1 * torch.sigmoid(x2)
436
+ x = residual + self.dropout(x)
437
+ return x
438
+
439
+
440
+ class ConvNorm(nn.Module):
441
+ def __init__(self,
442
+ in_channels,
443
+ out_channels,
444
+ kernel_size=1,
445
+ stride=1,
446
+ padding=None,
447
+ dilation=1,
448
+ bias=True,
449
+ spectral_norm=False,
450
+ ):
451
+ super(ConvNorm, self).__init__()
452
+
453
+ if padding is None:
454
+ assert (kernel_size % 2 == 1)
455
+ padding = int(dilation * (kernel_size - 1) / 2)
456
+
457
+ self.conv = torch.nn.Conv1d(in_channels,
458
+ out_channels,
459
+ kernel_size=kernel_size,
460
+ stride=stride,
461
+ padding=padding,
462
+ dilation=dilation,
463
+ bias=bias)
464
+
465
+ if spectral_norm:
466
+ self.conv = nn.utils.spectral_norm(self.conv)
467
+
468
+ def forward(self, input):
469
+ out = self.conv(input)
470
+ return out
471
+
472
+
473
+ class MultiHeadAttention(nn.Module):
474
+ ''' Multi-Head Attention module '''
475
+
476
+ def __init__(self, n_head, d_model, d_k, d_v, dropout=0., spectral_norm=False):
477
+ super().__init__()
478
+
479
+ self.n_head = n_head
480
+ self.d_k = d_k
481
+ self.d_v = d_v
482
+
483
+ self.w_qs = nn.Linear(d_model, n_head * d_k)
484
+ self.w_ks = nn.Linear(d_model, n_head * d_k)
485
+ self.w_vs = nn.Linear(d_model, n_head * d_v)
486
+
487
+ self.attention = ScaledDotProductAttention(temperature=np.power(d_model, 0.5), dropout=dropout)
488
+
489
+ self.fc = nn.Linear(n_head * d_v, d_model)
490
+ self.dropout = nn.Dropout(dropout)
491
+
492
+ if spectral_norm:
493
+ self.w_qs = nn.utils.spectral_norm(self.w_qs)
494
+ self.w_ks = nn.utils.spectral_norm(self.w_ks)
495
+ self.w_vs = nn.utils.spectral_norm(self.w_vs)
496
+ self.fc = nn.utils.spectral_norm(self.fc)
497
+
498
+ def forward(self, x, mask=None):
499
+ d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
500
+ sz_b, len_x, _ = x.size()
501
+
502
+ residual = x
503
+
504
+ q = self.w_qs(x).view(sz_b, len_x, n_head, d_k)
505
+ k = self.w_ks(x).view(sz_b, len_x, n_head, d_k)
506
+ v = self.w_vs(x).view(sz_b, len_x, n_head, d_v)
507
+ q = q.permute(2, 0, 1, 3).contiguous().view(-1,
508
+ len_x, d_k) # (n*b) x lq x dk
509
+ k = k.permute(2, 0, 1, 3).contiguous().view(-1,
510
+ len_x, d_k) # (n*b) x lk x dk
511
+ v = v.permute(2, 0, 1, 3).contiguous().view(-1,
512
+ len_x, d_v) # (n*b) x lv x dv
513
+
514
+ if mask is not None:
515
+ slf_mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..
516
+ else:
517
+ slf_mask = None
518
+ output, attn = self.attention(q, k, v, mask=slf_mask)
519
+
520
+ output = output.view(n_head, sz_b, len_x, d_v)
521
+ output = output.permute(1, 2, 0, 3).contiguous().view(
522
+ sz_b, len_x, -1) # b x lq x (n*dv)
523
+
524
+ output = self.fc(output)
525
+
526
+ output = self.dropout(output) + residual
527
+ return output, attn
528
+
529
+
530
+ class ScaledDotProductAttention(nn.Module):
531
+ ''' Scaled Dot-Product Attention '''
532
+
533
+ def __init__(self, temperature, dropout):
534
+ super().__init__()
535
+ self.temperature = temperature
536
+ self.softmax = nn.Softmax(dim=2)
537
+ self.dropout = nn.Dropout(dropout)
538
+
539
+ def forward(self, q, k, v, mask=None):
540
+ attn = torch.bmm(q, k.transpose(1, 2))
541
+ attn = attn / self.temperature
542
+
543
+ if mask is not None:
544
+ attn = attn.masked_fill(mask, -np.inf)
545
+
546
+ attn = self.softmax(attn)
547
+ p_attn = self.dropout(attn)
548
+
549
+ output = torch.bmm(p_attn, v)
550
+ return output, attn
551
+
552
+
553
+ class MelStyleEncoder(nn.Module):
554
+ ''' MelStyleEncoder '''
555
+
556
+ def __init__(self, n_mel_channels=80,
557
+ style_hidden=128,
558
+ style_vector_dim=256,
559
+ style_kernel_size=5,
560
+ style_head=2,
561
+ dropout=0.1):
562
+ super(MelStyleEncoder, self).__init__()
563
+ self.in_dim = n_mel_channels
564
+ self.hidden_dim = style_hidden
565
+ self.out_dim = style_vector_dim
566
+ self.kernel_size = style_kernel_size
567
+ self.n_head = style_head
568
+ self.dropout = dropout
569
+
570
+ self.spectral = nn.Sequential(
571
+ LinearNorm(self.in_dim, self.hidden_dim),
572
+ Mish(),
573
+ nn.Dropout(self.dropout),
574
+ LinearNorm(self.hidden_dim, self.hidden_dim),
575
+ Mish(),
576
+ nn.Dropout(self.dropout)
577
+ )
578
+
579
+ self.temporal = nn.Sequential(
580
+ Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
581
+ Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
582
+ )
583
+
584
+ self.slf_attn = MultiHeadAttention(self.n_head, self.hidden_dim,
585
+ self.hidden_dim // self.n_head, self.hidden_dim // self.n_head,
586
+ self.dropout)
587
+
588
+ self.fc = LinearNorm(self.hidden_dim, self.out_dim)
589
+
590
+ def temporal_avg_pool(self, x, mask=None):
591
+ if mask is None:
592
+ out = torch.mean(x, dim=1)
593
+ else:
594
+ len_ = (~mask).sum(dim=1).unsqueeze(1)
595
+ x = x.masked_fill(mask.unsqueeze(-1), 0)
596
+ x = x.sum(dim=1)
597
+ out = torch.div(x, len_)
598
+ return out
599
+
600
+ def forward(self, x, mask=None):
601
+ x = x.transpose(1,2)
602
+ if mask is not None:
603
+ mask = (mask.int()==0).squeeze(1)
604
+ max_len = x.shape[1]
605
+ slf_attn_mask = mask.unsqueeze(1).expand(-1, max_len, -1) if mask is not None else None
606
+
607
+ # spectral
608
+ x = self.spectral(x)
609
+ # temporal
610
+ x = x.transpose(1, 2)
611
+ x = self.temporal(x)
612
+ x = x.transpose(1, 2)
613
+ # self-attention
614
+ if mask is not None:
615
+ x = x.masked_fill(mask.unsqueeze(-1), 0)
616
+ x, _ = self.slf_attn(x, mask=slf_attn_mask)
617
+ # fc
618
+ x = self.fc(x)
619
+ # temoral average pooling
620
+ w = self.temporal_avg_pool(x, mask=mask)
621
+
622
+ return w.unsqueeze(-1)
623
+
624
+
625
+ class MelStyleEncoderVAE(nn.Module):
626
+ def __init__(self, spec_channels, z_latent_dim, emb_dim):
627
+ super().__init__()
628
+ self.ref_encoder = MelStyleEncoder(spec_channels, style_vector_dim=emb_dim)
629
+ self.fc1 = nn.Linear(emb_dim, z_latent_dim)
630
+ self.fc2 = nn.Linear(emb_dim, z_latent_dim)
631
+ self.fc3 = nn.Linear(z_latent_dim, emb_dim)
632
+ self.z_latent_dim = z_latent_dim
633
+
634
+ def reparameterize(self, mu, logvar):
635
+ if self.training:
636
+ std = torch.exp(0.5 * logvar)
637
+ eps = torch.randn_like(std)
638
+ return eps.mul(std).add_(mu)
639
+ else:
640
+ return mu
641
+
642
+ def forward(self, inputs, mask=None):
643
+ enc_out = self.ref_encoder(inputs.squeeze(-1), mask).squeeze(-1)
644
+ mu = self.fc1(enc_out)
645
+ logvar = self.fc2(enc_out)
646
+ posterior = D.Normal(mu, torch.exp(logvar))
647
+ kl_divergence = D.kl_divergence(posterior, D.Normal(torch.zeros_like(mu), torch.ones_like(logvar)))
648
+ loss_kl = kl_divergence.mean()
649
+
650
+ z = posterior.rsample()
651
+ style_embed = self.fc3(z)
652
+
653
+ return style_embed.unsqueeze(-1), loss_kl
654
+
655
+ def infer(self, inputs=None, random_sample=False, manual_latent=None):
656
+ if manual_latent is None:
657
+ if random_sample:
658
+ dev = next(self.parameters()).device
659
+ posterior = D.Normal(torch.zeros(1, self.z_latent_dim, device=dev),
660
+ torch.ones(1, self.z_latent_dim, device=dev))
661
+ z = posterior.rsample()
662
+ else:
663
+
664
+ enc_out = self.ref_encoder(inputs.transpose(1, 2))
665
+ mu = self.fc1(enc_out)
666
+ z = mu
667
+ else:
668
+ z = manual_latent
669
+ style_embed = self.fc3(z)
670
+ return style_embed.unsqueeze(-1), z
671
+
672
+
673
+ class ActNorm(nn.Module):
674
+ def __init__(self, channels, ddi=False, **kwargs):
675
+ super().__init__()
676
+ self.channels = channels
677
+ self.initialized = not ddi
678
+
679
+ self.logs = nn.Parameter(torch.zeros(1, channels, 1))
680
+ self.bias = nn.Parameter(torch.zeros(1, channels, 1))
681
+
682
+ def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):
683
+ if x_mask is None:
684
+ x_mask = torch.ones(x.size(0), 1, x.size(2)).to(device=x.device, dtype=x.dtype)
685
+ x_len = torch.sum(x_mask, [1, 2])
686
+ if not self.initialized:
687
+ self.initialize(x, x_mask)
688
+ self.initialized = True
689
+
690
+ if reverse:
691
+ z = (x - self.bias) * torch.exp(-self.logs) * x_mask
692
+ logdet = None
693
+ return z
694
+ else:
695
+ z = (self.bias + torch.exp(self.logs) * x) * x_mask
696
+ logdet = torch.sum(self.logs) * x_len # [b]
697
+ return z, logdet
698
+
699
+ def store_inverse(self):
700
+ pass
701
+
702
+ def set_ddi(self, ddi):
703
+ self.initialized = not ddi
704
+
705
+ def initialize(self, x, x_mask):
706
+ with torch.no_grad():
707
+ denom = torch.sum(x_mask, [0, 2])
708
+ m = torch.sum(x * x_mask, [0, 2]) / denom
709
+ m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom
710
+ v = m_sq - (m ** 2)
711
+ logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6))
712
+
713
+ bias_init = (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype)
714
+ logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype)
715
+
716
+ self.bias.data.copy_(bias_init)
717
+ self.logs.data.copy_(logs_init)
718
+
719
+
720
+ class InvConvNear(nn.Module):
721
+ def __init__(self, channels, n_split=4, no_jacobian=False, **kwargs):
722
+ super().__init__()
723
+ assert (n_split % 2 == 0)
724
+ self.channels = channels
725
+ self.n_split = n_split
726
+ self.no_jacobian = no_jacobian
727
+
728
+ w_init = torch.linalg.qr(torch.FloatTensor(self.n_split, self.n_split).normal_())[0]
729
+ if torch.det(w_init) < 0:
730
+ w_init[:, 0] = -1 * w_init[:, 0]
731
+ self.weight = nn.Parameter(w_init)
732
+
733
+ def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):
734
+ b, c, t = x.size()
735
+ assert (c % self.n_split == 0)
736
+ if x_mask is None:
737
+ x_mask = 1
738
+ x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t
739
+ else:
740
+ x_len = torch.sum(x_mask, [1, 2])
741
+
742
+ x = x.view(b, 2, c // self.n_split, self.n_split // 2, t)
743
+ x = x.permute(0, 1, 3, 2, 4).contiguous().view(b, self.n_split, c // self.n_split, t)
744
+
745
+ if reverse:
746
+ if hasattr(self, "weight_inv"):
747
+ weight = self.weight_inv
748
+ else:
749
+ weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)
750
+ logdet = None
751
+ else:
752
+ weight = self.weight
753
+ if self.no_jacobian:
754
+ logdet = 0
755
+ else:
756
+ logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len # [b]
757
+
758
+ weight = weight.view(self.n_split, self.n_split, 1, 1)
759
+ z = F.conv2d(x, weight)
760
+
761
+ z = z.view(b, 2, self.n_split // 2, c // self.n_split, t)
762
+ z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask
763
+ if reverse:
764
+ return z
765
+ else:
766
+ return z, logdet
767
+
768
+ def store_inverse(self):
769
+ self.weight_inv = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)
module/mrte_model.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is Multi-reference timbre encoder
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn.utils import remove_weight_norm, weight_norm
6
+ from module.attentions import MultiHeadAttention
7
+
8
+ class MRTE(nn.Module):
9
+ def __init__(self,
10
+ content_enc_channels=192,
11
+ hidden_size=512,
12
+ out_channels=192,
13
+ kernel_size=5,
14
+ n_heads=4,
15
+ ge_layer = 2
16
+ ):
17
+ super(MRTE, self).__init__()
18
+ self.cross_attention = MultiHeadAttention(hidden_size,hidden_size,n_heads)
19
+ self.c_pre = nn.Conv1d(content_enc_channels,hidden_size, 1)
20
+ self.text_pre = nn.Conv1d(content_enc_channels,hidden_size, 1)
21
+ self.c_post = nn.Conv1d(hidden_size,out_channels, 1)
22
+
23
+ def forward(self, ssl_enc, ssl_mask, text, text_mask, ge, test=None):
24
+ if(ge==None):ge=0
25
+ attn_mask = text_mask.unsqueeze(2) * ssl_mask.unsqueeze(-1)
26
+
27
+ ssl_enc = self.c_pre(ssl_enc * ssl_mask)
28
+ text_enc = self.text_pre(text * text_mask)
29
+ if test != None:
30
+ if test == 0:
31
+ x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
32
+ elif test == 1:
33
+ x = ssl_enc + ge
34
+ elif test ==2:
35
+ x = self.cross_attention(ssl_enc*0 * ssl_mask, text_enc * text_mask, attn_mask) + ge
36
+ else:
37
+ raise ValueError("test should be 0,1,2")
38
+ else:
39
+ x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
40
+ x = self.c_post(x * ssl_mask)
41
+ return x
42
+
43
+
44
+ class SpeakerEncoder(torch.nn.Module):
45
+ def __init__(self, mel_n_channels=80, model_num_layers=2, model_hidden_size=256, model_embedding_size=256):
46
+ super(SpeakerEncoder, self).__init__()
47
+ self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True)
48
+ self.linear = nn.Linear(model_hidden_size, model_embedding_size)
49
+ self.relu = nn.ReLU()
50
+
51
+ def forward(self, mels):
52
+ self.lstm.flatten_parameters()
53
+ _, (hidden, _) = self.lstm(mels.transpose(-1, -2))
54
+ embeds_raw = self.relu(self.linear(hidden[-1]))
55
+ return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)
56
+
57
+
58
+ class MELEncoder(nn.Module):
59
+ def __init__(self,
60
+ in_channels,
61
+ out_channels,
62
+ hidden_channels,
63
+ kernel_size,
64
+ dilation_rate,
65
+ n_layers):
66
+ super().__init__()
67
+ self.in_channels = in_channels
68
+ self.out_channels = out_channels
69
+ self.hidden_channels = hidden_channels
70
+ self.kernel_size = kernel_size
71
+ self.dilation_rate = dilation_rate
72
+ self.n_layers = n_layers
73
+
74
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
75
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers)
76
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
77
+
78
+ def forward(self, x):
79
+ # print(x.shape,x_lengths.shape)
80
+ x = self.pre(x)
81
+ x = self.enc(x)
82
+ x = self.proj(x)
83
+ return x
84
+
85
+
86
+ class WN(torch.nn.Module):
87
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers):
88
+ super(WN, self).__init__()
89
+ assert(kernel_size % 2 == 1)
90
+ self.hidden_channels =hidden_channels
91
+ self.kernel_size = kernel_size
92
+ self.dilation_rate = dilation_rate
93
+ self.n_layers = n_layers
94
+
95
+ self.in_layers = torch.nn.ModuleList()
96
+ self.res_skip_layers = torch.nn.ModuleList()
97
+
98
+ for i in range(n_layers):
99
+ dilation = dilation_rate ** i
100
+ padding = int((kernel_size * dilation - dilation) / 2)
101
+ in_layer = nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
102
+ dilation=dilation, padding=padding)
103
+ in_layer = weight_norm(in_layer)
104
+ self.in_layers.append(in_layer)
105
+
106
+ # last one is not necessary
107
+ if i < n_layers - 1:
108
+ res_skip_channels = 2 * hidden_channels
109
+ else:
110
+ res_skip_channels = hidden_channels
111
+
112
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
113
+ res_skip_layer = weight_norm(res_skip_layer, name='weight')
114
+ self.res_skip_layers.append(res_skip_layer)
115
+
116
+ def forward(self, x):
117
+ output = torch.zeros_like(x)
118
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
119
+
120
+ for i in range(self.n_layers):
121
+ x_in = self.in_layers[i](x)
122
+
123
+ acts = fused_add_tanh_sigmoid_multiply(
124
+ x_in,
125
+ n_channels_tensor)
126
+
127
+ res_skip_acts = self.res_skip_layers[i](acts)
128
+ if i < self.n_layers - 1:
129
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
130
+ x = (x + res_acts)
131
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
132
+ else:
133
+ output = output + res_skip_acts
134
+ return output
135
+
136
+ def remove_weight_norm(self):
137
+ for l in self.in_layers:
138
+ remove_weight_norm(l)
139
+ for l in self.res_skip_layers:
140
+ remove_weight_norm(l)
141
+
142
+
143
+ @torch.jit.script
144
+ def fused_add_tanh_sigmoid_multiply(input, n_channels):
145
+ n_channels_int = n_channels[0]
146
+ t_act = torch.tanh(input[:, :n_channels_int, :])
147
+ s_act = torch.sigmoid(input[:, n_channels_int:, :])
148
+ acts = t_act * s_act
149
+ return acts
150
+
151
+
152
+
153
+ if __name__ == '__main__':
154
+ content_enc = torch.randn(3,192,100)
155
+ content_mask = torch.ones(3,1,100)
156
+ ref_mel = torch.randn(3,128,30)
157
+ ref_mask = torch.ones(3,1,30)
158
+ model = MRTE()
159
+ out = model(content_enc,content_mask,ref_mel,ref_mask)
160
+ print(out.shape)
module/quantize.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Residual vector quantizer implementation."""
8
+
9
+ from dataclasses import dataclass, field
10
+ import math
11
+ import typing as tp
12
+
13
+ import torch
14
+ from torch import nn
15
+
16
+ from module.core_vq import ResidualVectorQuantization
17
+
18
+
19
+ @dataclass
20
+ class QuantizedResult:
21
+ quantized: torch.Tensor
22
+ codes: torch.Tensor
23
+ bandwidth: torch.Tensor # bandwidth in kb/s used, per batch item.
24
+ penalty: tp.Optional[torch.Tensor] = None
25
+ metrics: dict = field(default_factory=dict)
26
+
27
+
28
+ class ResidualVectorQuantizer(nn.Module):
29
+ """Residual Vector Quantizer.
30
+ Args:
31
+ dimension (int): Dimension of the codebooks.
32
+ n_q (int): Number of residual vector quantizers used.
33
+ bins (int): Codebook size.
34
+ decay (float): Decay for exponential moving average over the codebooks.
35
+ kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
36
+ kmeans_iters (int): Number of iterations used for kmeans initialization.
37
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
38
+ that have an exponential moving average cluster size less than the specified threshold with
39
+ randomly selected vector from the current batch.
40
+ """
41
+ def __init__(
42
+ self,
43
+ dimension: int = 256,
44
+ n_q: int = 8,
45
+ bins: int = 1024,
46
+ decay: float = 0.99,
47
+ kmeans_init: bool = True,
48
+ kmeans_iters: int = 50,
49
+ threshold_ema_dead_code: int = 2,
50
+ ):
51
+ super().__init__()
52
+ self.n_q = n_q
53
+ self.dimension = dimension
54
+ self.bins = bins
55
+ self.decay = decay
56
+ self.kmeans_init = kmeans_init
57
+ self.kmeans_iters = kmeans_iters
58
+ self.threshold_ema_dead_code = threshold_ema_dead_code
59
+ self.vq = ResidualVectorQuantization(
60
+ dim=self.dimension,
61
+ codebook_size=self.bins,
62
+ num_quantizers=self.n_q,
63
+ decay=self.decay,
64
+ kmeans_init=self.kmeans_init,
65
+ kmeans_iters=self.kmeans_iters,
66
+ threshold_ema_dead_code=self.threshold_ema_dead_code,
67
+ )
68
+
69
+ def forward(self, x: torch.Tensor, n_q: tp.Optional[int] = None, layers: tp.Optional[list] = None) -> QuantizedResult:
70
+ """Residual vector quantization on the given input tensor.
71
+ Args:
72
+ x (torch.Tensor): Input tensor.
73
+ n_q (int): Number of quantizer used to quantize. Default: All quantizers.
74
+ layers (list): Layer that need to return quantized. Defalt: None.
75
+ Returns:
76
+ QuantizedResult:
77
+ The quantized (or approximately quantized) representation with
78
+ the associated numbert quantizers and layer quantized required to return.
79
+ """
80
+ n_q = n_q if n_q else self.n_q
81
+ if layers and max(layers) >= n_q:
82
+ raise ValueError(f'Last layer index in layers: A {max(layers)}. Number of quantizers in RVQ: B {self.n_q}. A must less than B.')
83
+ quantized, codes, commit_loss, quantized_list = self.vq(x, n_q=n_q, layers=layers)
84
+ return quantized, codes, torch.mean(commit_loss), quantized_list
85
+
86
+
87
+ def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None, st: tp.Optional[int] = None) -> torch.Tensor:
88
+ """Encode a given input tensor with the specified sample rate at the given bandwidth.
89
+ The RVQ encode method sets the appropriate number of quantizer to use
90
+ and returns indices for each quantizer.
91
+ Args:
92
+ x (torch.Tensor): Input tensor.
93
+ n_q (int): Number of quantizer used to quantize. Default: All quantizers.
94
+ st (int): Start to encode input from which layers. Default: 0.
95
+ """
96
+ n_q = n_q if n_q else self.n_q
97
+ st = st or 0
98
+ codes = self.vq.encode(x, n_q=n_q, st=st)
99
+ return codes
100
+
101
+ def decode(self, codes: torch.Tensor, st: int = 0) -> torch.Tensor:
102
+ """Decode the given codes to the quantized representation.
103
+ Args:
104
+ codes (torch.Tensor): Input indices for each quantizer.
105
+ st (int): Start to decode input codes from which layers. Default: 0.
106
+ """
107
+ quantized = self.vq.decode(codes, st=st)
108
+ return quantized
module/transforms.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import numpy as np
5
+
6
+
7
+ DEFAULT_MIN_BIN_WIDTH = 1e-3
8
+ DEFAULT_MIN_BIN_HEIGHT = 1e-3
9
+ DEFAULT_MIN_DERIVATIVE = 1e-3
10
+
11
+
12
+ def piecewise_rational_quadratic_transform(inputs,
13
+ unnormalized_widths,
14
+ unnormalized_heights,
15
+ unnormalized_derivatives,
16
+ inverse=False,
17
+ tails=None,
18
+ tail_bound=1.,
19
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
20
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
21
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
22
+
23
+ if tails is None:
24
+ spline_fn = rational_quadratic_spline
25
+ spline_kwargs = {}
26
+ else:
27
+ spline_fn = unconstrained_rational_quadratic_spline
28
+ spline_kwargs = {
29
+ 'tails': tails,
30
+ 'tail_bound': tail_bound
31
+ }
32
+
33
+ outputs, logabsdet = spline_fn(
34
+ inputs=inputs,
35
+ unnormalized_widths=unnormalized_widths,
36
+ unnormalized_heights=unnormalized_heights,
37
+ unnormalized_derivatives=unnormalized_derivatives,
38
+ inverse=inverse,
39
+ min_bin_width=min_bin_width,
40
+ min_bin_height=min_bin_height,
41
+ min_derivative=min_derivative,
42
+ **spline_kwargs
43
+ )
44
+ return outputs, logabsdet
45
+
46
+
47
+ def searchsorted(bin_locations, inputs, eps=1e-6):
48
+ bin_locations[..., -1] += eps
49
+ return torch.sum(
50
+ inputs[..., None] >= bin_locations,
51
+ dim=-1
52
+ ) - 1
53
+
54
+
55
+ def unconstrained_rational_quadratic_spline(inputs,
56
+ unnormalized_widths,
57
+ unnormalized_heights,
58
+ unnormalized_derivatives,
59
+ inverse=False,
60
+ tails='linear',
61
+ tail_bound=1.,
62
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
63
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
64
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
65
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
66
+ outside_interval_mask = ~inside_interval_mask
67
+
68
+ outputs = torch.zeros_like(inputs)
69
+ logabsdet = torch.zeros_like(inputs)
70
+
71
+ if tails == 'linear':
72
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
73
+ constant = np.log(np.exp(1 - min_derivative) - 1)
74
+ unnormalized_derivatives[..., 0] = constant
75
+ unnormalized_derivatives[..., -1] = constant
76
+
77
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
78
+ logabsdet[outside_interval_mask] = 0
79
+ else:
80
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
81
+
82
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
83
+ inputs=inputs[inside_interval_mask],
84
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
85
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
86
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
87
+ inverse=inverse,
88
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
89
+ min_bin_width=min_bin_width,
90
+ min_bin_height=min_bin_height,
91
+ min_derivative=min_derivative
92
+ )
93
+
94
+ return outputs, logabsdet
95
+
96
+ def rational_quadratic_spline(inputs,
97
+ unnormalized_widths,
98
+ unnormalized_heights,
99
+ unnormalized_derivatives,
100
+ inverse=False,
101
+ left=0., right=1., bottom=0., top=1.,
102
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
103
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
104
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
105
+ if torch.min(inputs) < left or torch.max(inputs) > right:
106
+ raise ValueError('Input to a transform is not within its domain')
107
+
108
+ num_bins = unnormalized_widths.shape[-1]
109
+
110
+ if min_bin_width * num_bins > 1.0:
111
+ raise ValueError('Minimal bin width too large for the number of bins')
112
+ if min_bin_height * num_bins > 1.0:
113
+ raise ValueError('Minimal bin height too large for the number of bins')
114
+
115
+ widths = F.softmax(unnormalized_widths, dim=-1)
116
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
117
+ cumwidths = torch.cumsum(widths, dim=-1)
118
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
119
+ cumwidths = (right - left) * cumwidths + left
120
+ cumwidths[..., 0] = left
121
+ cumwidths[..., -1] = right
122
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
123
+
124
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
125
+
126
+ heights = F.softmax(unnormalized_heights, dim=-1)
127
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
128
+ cumheights = torch.cumsum(heights, dim=-1)
129
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
130
+ cumheights = (top - bottom) * cumheights + bottom
131
+ cumheights[..., 0] = bottom
132
+ cumheights[..., -1] = top
133
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
134
+
135
+ if inverse:
136
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
137
+ else:
138
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
139
+
140
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
141
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
142
+
143
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
144
+ delta = heights / widths
145
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
146
+
147
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
148
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
149
+
150
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
151
+
152
+ if inverse:
153
+ a = (((inputs - input_cumheights) * (input_derivatives
154
+ + input_derivatives_plus_one
155
+ - 2 * input_delta)
156
+ + input_heights * (input_delta - input_derivatives)))
157
+ b = (input_heights * input_derivatives
158
+ - (inputs - input_cumheights) * (input_derivatives
159
+ + input_derivatives_plus_one
160
+ - 2 * input_delta))
161
+ c = - input_delta * (inputs - input_cumheights)
162
+
163
+ discriminant = b.pow(2) - 4 * a * c
164
+ assert (discriminant >= 0).all()
165
+
166
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
167
+ outputs = root * input_bin_widths + input_cumwidths
168
+
169
+ theta_one_minus_theta = root * (1 - root)
170
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
171
+ * theta_one_minus_theta)
172
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
173
+ + 2 * input_delta * theta_one_minus_theta
174
+ + input_derivatives * (1 - root).pow(2))
175
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
176
+
177
+ return outputs, -logabsdet
178
+ else:
179
+ theta = (inputs - input_cumwidths) / input_bin_widths
180
+ theta_one_minus_theta = theta * (1 - theta)
181
+
182
+ numerator = input_heights * (input_delta * theta.pow(2)
183
+ + input_derivatives * theta_one_minus_theta)
184
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
185
+ * theta_one_minus_theta)
186
+ outputs = input_cumheights + numerator / denominator
187
+
188
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
189
+ + 2 * input_delta * theta_one_minus_theta
190
+ + input_derivatives * (1 - theta).pow(2))
191
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
192
+
193
+ return outputs, logabsdet
my_utils.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ffmpeg
2
+ import numpy as np
3
+
4
+
5
+ def load_audio(file, sr):
6
+ try:
7
+ # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
8
+ # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
9
+ # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
10
+ file = (
11
+ file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
12
+ ) # 防止小白拷路径头尾带了空格和"和回车
13
+ out, _ = (
14
+ ffmpeg.input(file, threads=0)
15
+ .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
16
+ .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
17
+ )
18
+ except Exception as e:
19
+ raise RuntimeError(f"Failed to load audio: {e}")
20
+
21
+ return np.frombuffer(out, np.float32).flatten()
pretrained_models/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
pretrained_models/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
4
+ pretrained models used in https://github.com/RVC-Boss/GPT-SoVITS
pretrained_models/chinese-hubert-base/config.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/docker/liujing04/gpt-vits/chinese-hubert-base",
3
+ "activation_dropout": 0.1,
4
+ "apply_spec_augment": true,
5
+ "architectures": [
6
+ "HubertModel"
7
+ ],
8
+ "attention_dropout": 0.1,
9
+ "bos_token_id": 1,
10
+ "classifier_proj_size": 256,
11
+ "conv_bias": false,
12
+ "conv_dim": [
13
+ 512,
14
+ 512,
15
+ 512,
16
+ 512,
17
+ 512,
18
+ 512,
19
+ 512
20
+ ],
21
+ "conv_kernel": [
22
+ 10,
23
+ 3,
24
+ 3,
25
+ 3,
26
+ 3,
27
+ 2,
28
+ 2
29
+ ],
30
+ "conv_stride": [
31
+ 5,
32
+ 2,
33
+ 2,
34
+ 2,
35
+ 2,
36
+ 2,
37
+ 2
38
+ ],
39
+ "ctc_loss_reduction": "sum",
40
+ "ctc_zero_infinity": false,
41
+ "do_stable_layer_norm": false,
42
+ "eos_token_id": 2,
43
+ "feat_extract_activation": "gelu",
44
+ "feat_extract_norm": "group",
45
+ "feat_proj_dropout": 0.0,
46
+ "feat_proj_layer_norm": true,
47
+ "final_dropout": 0.1,
48
+ "hidden_act": "gelu",
49
+ "hidden_dropout": 0.1,
50
+ "hidden_size": 768,
51
+ "initializer_range": 0.02,
52
+ "intermediate_size": 3072,
53
+ "layer_norm_eps": 1e-05,
54
+ "layerdrop": 0.1,
55
+ "mask_feature_length": 10,
56
+ "mask_feature_min_masks": 0,
57
+ "mask_feature_prob": 0.0,
58
+ "mask_time_length": 10,
59
+ "mask_time_min_masks": 2,
60
+ "mask_time_prob": 0.05,
61
+ "model_type": "hubert",
62
+ "num_attention_heads": 12,
63
+ "num_conv_pos_embedding_groups": 16,
64
+ "num_conv_pos_embeddings": 128,
65
+ "num_feat_extract_layers": 7,
66
+ "num_hidden_layers": 12,
67
+ "pad_token_id": 0,
68
+ "torch_dtype": "float16",
69
+ "transformers_version": "4.30.2",
70
+ "use_weighted_layer_sum": false,
71
+ "vocab_size": 32
72
+ }