kevinwang676 commited on
Commit
a099bcc
·
verified ·
1 Parent(s): 0282784

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. GPT_SoVITS/AR/__init__.py +0 -0
  2. GPT_SoVITS/AR/data/__init__.py +0 -0
  3. GPT_SoVITS/AR/data/bucket_sampler.py +149 -0
  4. GPT_SoVITS/AR/data/data_module.py +81 -0
  5. GPT_SoVITS/AR/data/dataset.py +320 -0
  6. GPT_SoVITS/AR/models/__init__.py +0 -0
  7. GPT_SoVITS/AR/models/t2s_lightning_module.py +145 -0
  8. GPT_SoVITS/AR/models/t2s_lightning_module_onnx.py +110 -0
  9. GPT_SoVITS/AR/models/t2s_model.py +935 -0
  10. GPT_SoVITS/AR/models/t2s_model_onnx.py +394 -0
  11. GPT_SoVITS/AR/models/utils.py +282 -0
  12. GPT_SoVITS/AR/modules/__init__.py +0 -0
  13. GPT_SoVITS/AR/modules/activation.py +413 -0
  14. GPT_SoVITS/AR/modules/activation_onnx.py +188 -0
  15. GPT_SoVITS/AR/modules/embedding.py +78 -0
  16. GPT_SoVITS/AR/modules/embedding_onnx.py +63 -0
  17. GPT_SoVITS/AR/modules/lr_schedulers.py +85 -0
  18. GPT_SoVITS/AR/modules/optim.py +593 -0
  19. GPT_SoVITS/AR/modules/patched_mha_with_cache.py +428 -0
  20. GPT_SoVITS/AR/modules/patched_mha_with_cache_onnx.py +85 -0
  21. GPT_SoVITS/AR/modules/scaling.py +320 -0
  22. GPT_SoVITS/AR/modules/transformer.py +362 -0
  23. GPT_SoVITS/AR/modules/transformer_onnx.py +281 -0
  24. GPT_SoVITS/AR/text_processing/__init__.py +0 -0
  25. GPT_SoVITS/AR/text_processing/phonemizer.py +72 -0
  26. GPT_SoVITS/AR/text_processing/symbols.py +12 -0
  27. GPT_SoVITS/AR/utils/__init__.py +36 -0
  28. GPT_SoVITS/AR/utils/initialize.py +39 -0
  29. GPT_SoVITS/AR/utils/io.py +30 -0
  30. GPT_SoVITS/feature_extractor/__init__.py +3 -0
  31. GPT_SoVITS/feature_extractor/cnhubert.py +106 -0
  32. GPT_SoVITS/feature_extractor/whisper_enc.py +23 -0
  33. GPT_SoVITS/module/__init__.py +0 -0
  34. GPT_SoVITS/module/attentions.py +659 -0
  35. GPT_SoVITS/module/attentions_onnx.py +385 -0
  36. GPT_SoVITS/module/commons.py +185 -0
  37. GPT_SoVITS/module/core_vq.py +365 -0
  38. GPT_SoVITS/module/data_utils.py +1027 -0
  39. GPT_SoVITS/module/losses.py +70 -0
  40. GPT_SoVITS/module/mel_processing.py +111 -0
  41. GPT_SoVITS/module/models.py +1378 -0
  42. GPT_SoVITS/module/models_onnx.py +1070 -0
  43. GPT_SoVITS/module/modules.py +895 -0
  44. GPT_SoVITS/module/mrte_model.py +173 -0
  45. GPT_SoVITS/module/quantize.py +114 -0
  46. GPT_SoVITS/module/transforms.py +205 -0
  47. GPT_SoVITS/prepare_datasets/1-get-text.py +143 -0
  48. GPT_SoVITS/prepare_datasets/2-get-hubert-wav32k.py +134 -0
  49. GPT_SoVITS/prepare_datasets/3-get-semantic.py +118 -0
  50. GPT_SoVITS/text/G2PWModel/MONOPHONIC_CHARS.txt +0 -0
GPT_SoVITS/AR/__init__.py ADDED
File without changes
GPT_SoVITS/AR/data/__init__.py ADDED
File without changes
GPT_SoVITS/AR/data/bucket_sampler.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/bucket_sampler.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import itertools
4
+ import math
5
+ import random
6
+ from random import shuffle
7
+ from typing import Iterator, Optional, TypeVar
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ from torch.utils.data import Dataset, Sampler
12
+
13
+ __all__ = [
14
+ "DistributedBucketSampler",
15
+ ]
16
+
17
+ T_co = TypeVar("T_co", covariant=True)
18
+
19
+
20
+ class DistributedBucketSampler(Sampler[T_co]):
21
+ r"""
22
+ sort the dataset wrt. input length
23
+ divide samples into buckets
24
+ sort within buckets
25
+ divide buckets into batches
26
+ sort batches
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ dataset: Dataset,
32
+ num_replicas: Optional[int] = None,
33
+ rank: Optional[int] = None,
34
+ shuffle: bool = True,
35
+ seed: int = 0,
36
+ drop_last: bool = False,
37
+ batch_size: int = 32,
38
+ ) -> None:
39
+ if num_replicas is None:
40
+ if not dist.is_available():
41
+ raise RuntimeError("Requires distributed package to be available")
42
+ num_replicas = dist.get_world_size() if torch.cuda.is_available() else 1
43
+ if rank is None:
44
+ if not dist.is_available():
45
+ raise RuntimeError("Requires distributed package to be available")
46
+ rank = dist.get_rank() if torch.cuda.is_available() else 0
47
+ if torch.cuda.is_available():
48
+ torch.cuda.set_device(rank)
49
+ if rank >= num_replicas or rank < 0:
50
+ raise ValueError("Invalid rank {}, rank should be in the interval [0, {}]".format(rank, num_replicas - 1))
51
+ self.dataset = dataset
52
+ self.num_replicas = num_replicas
53
+ self.rank = rank
54
+ self.epoch = 0
55
+ self.drop_last = drop_last
56
+ # If the dataset length is evenly divisible by # of replicas, then there
57
+ # is no need to drop any data, since the dataset will be split equally.
58
+ if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type]
59
+ # Split to nearest available length that is evenly divisible.
60
+ # This is to ensure each rank receives the same amount of data when
61
+ # using this Sampler.
62
+ self.num_samples = math.ceil(
63
+ (len(self.dataset) - self.num_replicas) / self.num_replicas, # type: ignore[arg-type]
64
+ )
65
+ else:
66
+ self.num_samples = math.ceil(
67
+ len(self.dataset) / self.num_replicas,
68
+ ) # type: ignore[arg-type]
69
+ self.total_size = self.num_samples * self.num_replicas
70
+ self.shuffle = shuffle
71
+ self.seed = seed
72
+ self.batch_size = batch_size
73
+ self.id_with_length = self._get_sample_lengths()
74
+ self.id_buckets = self.make_buckets(bucket_width=2.0)
75
+
76
+ def _get_sample_lengths(self):
77
+ id_with_lengths = []
78
+ for i in range(len(self.dataset)):
79
+ id_with_lengths.append((i, self.dataset.get_sample_length(i)))
80
+ id_with_lengths.sort(key=lambda x: x[1])
81
+ return id_with_lengths
82
+
83
+ def make_buckets(self, bucket_width: float = 2.0):
84
+ buckets = []
85
+ cur = []
86
+ max_sec = bucket_width
87
+ for id, sec in self.id_with_length:
88
+ if sec < max_sec:
89
+ cur.append(id)
90
+ else:
91
+ buckets.append(cur)
92
+ cur = [id]
93
+ max_sec += bucket_width
94
+ if len(cur) > 0:
95
+ buckets.append(cur)
96
+ return buckets
97
+
98
+ def __iter__(self) -> Iterator[T_co]:
99
+ if self.shuffle:
100
+ # deterministically shuffle based on epoch and seed
101
+ g = torch.Generator()
102
+ g.manual_seed(self.seed + self.epoch)
103
+ random.seed(self.epoch + self.seed)
104
+ shuffled_bucket = []
105
+ for buc in self.id_buckets:
106
+ buc_copy = buc.copy()
107
+ shuffle(buc_copy)
108
+ shuffled_bucket.append(buc_copy)
109
+ grouped_batch_size = self.batch_size * self.num_replicas
110
+ shuffled_bucket = list(itertools.chain(*shuffled_bucket))
111
+ n_batch = int(math.ceil(len(shuffled_bucket) / grouped_batch_size))
112
+ batches = [shuffled_bucket[b * grouped_batch_size : (b + 1) * grouped_batch_size] for b in range(n_batch)]
113
+ shuffle(batches)
114
+ indices = list(itertools.chain(*batches))
115
+ else:
116
+ # type: ignore[arg-type]
117
+ indices = list(range(len(self.dataset)))
118
+
119
+ if not self.drop_last:
120
+ # add extra samples to make it evenly divisible
121
+ padding_size = self.total_size - len(indices)
122
+ if padding_size <= len(indices):
123
+ indices += indices[:padding_size]
124
+ else:
125
+ indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
126
+ else:
127
+ # remove tail of data to make it evenly divisible.
128
+ indices = indices[: self.total_size]
129
+ assert len(indices) == self.total_size
130
+
131
+ # subsample
132
+ indices = indices[self.rank : self.total_size : self.num_replicas]
133
+ assert len(indices) == self.num_samples
134
+
135
+ return iter(indices)
136
+
137
+ def __len__(self) -> int:
138
+ return self.num_samples
139
+
140
+ def set_epoch(self, epoch: int) -> None:
141
+ r"""
142
+ Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
143
+ use a different random ordering for each epoch. Otherwise, the next iteration of this
144
+ sampler will yield the same ordering.
145
+
146
+ Args:
147
+ epoch (int): Epoch number.
148
+ """
149
+ self.epoch = epoch
GPT_SoVITS/AR/data/data_module.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/data_module.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ from pytorch_lightning import LightningDataModule
4
+ from torch.utils.data import DataLoader
5
+
6
+ from AR.data.bucket_sampler import DistributedBucketSampler
7
+ from AR.data.dataset import Text2SemanticDataset
8
+
9
+
10
+ class Text2SemanticDataModule(LightningDataModule):
11
+ def __init__(
12
+ self,
13
+ config,
14
+ train_semantic_path,
15
+ train_phoneme_path,
16
+ dev_semantic_path=None,
17
+ dev_phoneme_path=None,
18
+ ):
19
+ super().__init__()
20
+ self.config = config
21
+ self.train_semantic_path = train_semantic_path
22
+ self.train_phoneme_path = train_phoneme_path
23
+ self.dev_semantic_path = dev_semantic_path
24
+ self.dev_phoneme_path = dev_phoneme_path
25
+ self.num_workers = self.config["data"]["num_workers"]
26
+
27
+ def prepare_data(self):
28
+ pass
29
+
30
+ def setup(self, stage=None, output_logs=False):
31
+ self._train_dataset = Text2SemanticDataset(
32
+ phoneme_path=self.train_phoneme_path,
33
+ semantic_path=self.train_semantic_path,
34
+ max_sec=self.config["data"]["max_sec"],
35
+ pad_val=self.config["data"]["pad_val"],
36
+ )
37
+ self._dev_dataset = self._train_dataset
38
+ # self._dev_dataset = Text2SemanticDataset(
39
+ # phoneme_path=self.dev_phoneme_path,
40
+ # semantic_path=self.dev_semantic_path,
41
+ # max_sample=self.config['data']['max_eval_sample'],
42
+ # max_sec=self.config['data']['max_sec'],
43
+ # pad_val=self.config['data']['pad_val'])
44
+
45
+ def train_dataloader(self):
46
+ batch_size = (
47
+ self.config["train"]["batch_size"] // 2
48
+ if self.config["train"].get("if_dpo", False) is True
49
+ else self.config["train"]["batch_size"]
50
+ )
51
+ batch_size = max(min(batch_size, len(self._train_dataset) // 4), 1) # 防止不保存
52
+ sampler = DistributedBucketSampler(self._train_dataset, batch_size=batch_size)
53
+ return DataLoader(
54
+ self._train_dataset,
55
+ batch_size=batch_size,
56
+ sampler=sampler,
57
+ collate_fn=self._train_dataset.collate,
58
+ num_workers=self.num_workers,
59
+ persistent_workers=True,
60
+ prefetch_factor=16,
61
+ )
62
+
63
+ def val_dataloader(self):
64
+ return DataLoader(
65
+ self._dev_dataset,
66
+ batch_size=1,
67
+ shuffle=False,
68
+ collate_fn=self._train_dataset.collate,
69
+ num_workers=max(self.num_workers, 12),
70
+ persistent_workers=True,
71
+ prefetch_factor=16,
72
+ )
73
+
74
+ # 这个会使用到嘛?
75
+ def test_dataloader(self):
76
+ return DataLoader(
77
+ self._dev_dataset,
78
+ batch_size=1,
79
+ shuffle=False,
80
+ collate_fn=self._train_dataset.collate,
81
+ )
GPT_SoVITS/AR/data/dataset.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/dataset.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+
4
+ # sys.path.append("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert")
5
+ import os
6
+ import traceback
7
+ from typing import Dict, List
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ import torch
12
+ from torch.utils.data import DataLoader, Dataset
13
+
14
+ version = os.environ.get("version", None)
15
+
16
+ from text import cleaned_text_to_sequence
17
+
18
+ # from config import exp_dir
19
+
20
+
21
+ def batch_sequences(sequences: List[np.array], axis: int = 0, pad_value: int = 0):
22
+ seq = sequences[0]
23
+ ndim = seq.ndim
24
+ if axis < 0:
25
+ axis += ndim
26
+ dtype = seq.dtype
27
+ pad_value = dtype.type(pad_value)
28
+ seq_lengths = [seq.shape[axis] for seq in sequences]
29
+ max_length = np.max(seq_lengths)
30
+
31
+ padded_sequences = []
32
+ for seq, length in zip(sequences, seq_lengths):
33
+ padding = [(0, 0)] * axis + [(0, max_length - length)] + [(0, 0)] * (ndim - axis - 1)
34
+ padded_seq = np.pad(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
+
40
+ class Text2SemanticDataset(Dataset):
41
+ """dataset class for text tokens to semantic model training."""
42
+
43
+ def __init__(
44
+ self,
45
+ phoneme_path: str,
46
+ semantic_path: str,
47
+ max_sample: int = None,
48
+ max_sec: int = 100,
49
+ pad_val: int = 1024,
50
+ # min value of phoneme/sec
51
+ min_ps_ratio: int = 3,
52
+ # max value of phoneme/sec
53
+ max_ps_ratio: int = 25,
54
+ ) -> None:
55
+ super().__init__()
56
+
57
+ self.semantic_data = pd.read_csv(
58
+ semantic_path,
59
+ delimiter="\t",
60
+ encoding="utf-8",
61
+ )
62
+ # get dict
63
+ self.path2 = phoneme_path # "%s/2-name2text.txt"%exp_dir#phoneme_path
64
+ self.path3 = "%s/3-bert" % (
65
+ os.path.dirname(
66
+ phoneme_path,
67
+ )
68
+ ) # "%s/3-bert"%exp_dir#bert_dir
69
+ self.path6 = semantic_path # "%s/6-name2semantic.tsv"%exp_dir#semantic_path
70
+ assert os.path.exists(self.path2)
71
+ assert os.path.exists(self.path6)
72
+ self.phoneme_data = {}
73
+ with open(self.path2, "r", encoding="utf8") as f:
74
+ lines = f.read().strip("\n").split("\n")
75
+
76
+ for line in lines:
77
+ tmp = line.split("\t")
78
+ if len(tmp) != 4:
79
+ continue
80
+ self.phoneme_data[tmp[0]] = [tmp[1], tmp[2], tmp[3]]
81
+
82
+ # self.phoneme_data = np.load(phoneme_path, allow_pickle=True).item()
83
+ # pad for semantic tokens
84
+ self.PAD: int = pad_val
85
+ # self.hz = 25
86
+ # with open("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert/configs/s2.json", "r") as f:data = f.read()
87
+ # data=json.loads(data)["model"]["semantic_frame_rate"]#50hz
88
+ # self.hz=int(data[:-2])#
89
+ self.hz = int(os.environ.get("hz", "25hz")[:-2])
90
+
91
+ # max seconds of semantic token
92
+ self.max_sec = max_sec
93
+ self.min_ps_ratio = min_ps_ratio
94
+ self.max_ps_ratio = max_ps_ratio
95
+
96
+ if max_sample is not None:
97
+ self.semantic_data = self.semantic_data[:max_sample]
98
+
99
+ # {idx: (semantic, phoneme)}
100
+ # semantic list, phoneme list
101
+ self.semantic_phoneme = []
102
+ self.item_names = []
103
+
104
+ self.inited = False
105
+
106
+ if not self.inited:
107
+ # 调用初始化函数
108
+ self.init_batch()
109
+ self.inited = True
110
+ del self.semantic_data
111
+ del self.phoneme_data
112
+ # self.tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext-large")
113
+ # self.tokenizer = AutoTokenizer.from_pretrained("/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large")
114
+
115
+ def init_batch(self):
116
+ semantic_data_len = len(self.semantic_data)
117
+ phoneme_data_len = len(self.phoneme_data.keys())
118
+ print("semantic_data_len:", semantic_data_len)
119
+ print("phoneme_data_len:", phoneme_data_len)
120
+ print(self.semantic_data)
121
+ idx = 0
122
+ num_not_in = 0
123
+ num_deleted_bigger = 0
124
+ num_deleted_ps = 0
125
+ for i in range(semantic_data_len):
126
+ # 先依次遍历
127
+ # get str
128
+ item_name = self.semantic_data.iloc[i, 0]
129
+ # print(self.phoneme_data)
130
+ try:
131
+ phoneme, word2ph, text = self.phoneme_data[item_name]
132
+ except Exception:
133
+ traceback.print_exc()
134
+ # print(f"{item_name} not in self.phoneme_data !")
135
+ num_not_in += 1
136
+ continue
137
+
138
+ semantic_str = self.semantic_data.iloc[i, 1]
139
+ # get token list
140
+ semantic_ids = [int(idx) for idx in semantic_str.split(" ")]
141
+ # (T), 是否需要变成 (1, T) -> 不需要,因为需要求 len
142
+ # 过滤掉太长的样��
143
+ if (
144
+ len(semantic_ids) > self.max_sec * self.hz
145
+ ): #########1###根据token个数推测总时长过滤时长60s(config里)#40*25=1k
146
+ num_deleted_bigger += 1
147
+ continue
148
+ # (T, ), 这个速度不会很慢,所以可以在一开始就处理,无需在 __getitem__ 里面单个处理####
149
+ phoneme = phoneme.split(" ")
150
+
151
+ try:
152
+ phoneme_ids = cleaned_text_to_sequence(phoneme, version)
153
+ except:
154
+ traceback.print_exc()
155
+ # print(f"{item_name} not in self.phoneme_data !")
156
+ num_not_in += 1
157
+ continue
158
+ # if len(phoneme_ids) >400:###########2:改为恒定限制为semantic/2.5就行
159
+ if len(phoneme_ids) > self.max_sec * self.hz / 2.5: ###########2:改为恒定限制为semantic/2.5就行
160
+ num_deleted_ps += 1
161
+ continue
162
+ # if len(semantic_ids) > 1000:###########3
163
+ # num_deleted_bigger += 1
164
+ # continue
165
+
166
+ ps_ratio = len(phoneme_ids) / (len(semantic_ids) / self.hz)
167
+
168
+ if ps_ratio > self.max_ps_ratio or ps_ratio < self.min_ps_ratio: ##########4#3~25#每秒多少个phone
169
+ num_deleted_ps += 1
170
+ # print(item_name)
171
+ continue
172
+
173
+ self.semantic_phoneme.append((semantic_ids, phoneme_ids))
174
+ idx += 1
175
+ self.item_names.append(item_name)
176
+
177
+ min_num = 100 # 20直接不补#30补了也不存ckpt
178
+ leng = len(self.semantic_phoneme)
179
+ if leng < min_num:
180
+ tmp1 = self.semantic_phoneme
181
+ tmp2 = self.item_names
182
+ self.semantic_phoneme = []
183
+ self.item_names = []
184
+ for _ in range(max(2, int(min_num / leng))):
185
+ self.semantic_phoneme += tmp1
186
+ self.item_names += tmp2
187
+ if num_not_in > 0:
188
+ print(f"there are {num_not_in} semantic datas not in phoneme datas")
189
+ if num_deleted_bigger > 0:
190
+ print(
191
+ f"deleted {num_deleted_bigger} audios who's duration are bigger than {self.max_sec} seconds",
192
+ )
193
+ if num_deleted_ps > 0:
194
+ # 4702 for LibriTTS, LirbriTTS 是标注数据, 是否需要筛?=> 需要,有值为 100 的极端值
195
+ print(
196
+ f"deleted {num_deleted_ps} audios who's phoneme/sec are bigger than {self.max_ps_ratio} or smaller than {self.min_ps_ratio}",
197
+ )
198
+ """
199
+ there are 31 semantic datas not in phoneme datas
200
+ deleted 34 audios who's duration are bigger than 54 seconds
201
+ deleted 3190 audios who's phoneme/sec are bigger than 25 or smaller than 3
202
+ dataset.__len__(): 366463
203
+
204
+ """
205
+ # 345410 for LibriTTS
206
+ print("dataset.__len__():", self.__len__())
207
+
208
+ def __get_item_names__(self) -> List[str]:
209
+ return self.item_names
210
+
211
+ def __len__(self) -> int:
212
+ return len(self.semantic_phoneme)
213
+
214
+ def __getitem__(self, idx: int) -> Dict:
215
+ semantic_ids, phoneme_ids = self.semantic_phoneme[idx]
216
+ item_name = self.item_names[idx]
217
+ phoneme_ids_len = len(phoneme_ids)
218
+ # semantic tokens target
219
+ semantic_ids_len = len(semantic_ids)
220
+
221
+ flag = 0
222
+ path_bert = "%s/%s.pt" % (self.path3, item_name)
223
+ if os.path.exists(path_bert) == True:
224
+ bert_feature = torch.load(path_bert, map_location="cpu")
225
+ else:
226
+ flag = 1
227
+ if flag == 1:
228
+ # bert_feature=torch.zeros_like(phoneme_ids,dtype=torch.float32)
229
+ bert_feature = None
230
+ else:
231
+ assert bert_feature.shape[-1] == len(phoneme_ids)
232
+ return {
233
+ "idx": idx,
234
+ "phoneme_ids": phoneme_ids,
235
+ "phoneme_ids_len": phoneme_ids_len,
236
+ "semantic_ids": semantic_ids,
237
+ "semantic_ids_len": semantic_ids_len,
238
+ "bert_feature": bert_feature,
239
+ }
240
+
241
+ def get_sample_length(self, idx: int):
242
+ semantic_ids = self.semantic_phoneme[idx][0]
243
+ sec = 1.0 * len(semantic_ids) / self.hz
244
+ return sec
245
+
246
+ def collate(self, examples: List[Dict]) -> Dict:
247
+ sample_index: List[int] = []
248
+ phoneme_ids: List[torch.Tensor] = []
249
+ phoneme_ids_lens: List[int] = []
250
+ semantic_ids: List[torch.Tensor] = []
251
+ semantic_ids_lens: List[int] = []
252
+ # return
253
+
254
+ for item in examples:
255
+ sample_index.append(item["idx"])
256
+ phoneme_ids.append(np.array(item["phoneme_ids"], dtype=np.int64))
257
+ semantic_ids.append(np.array(item["semantic_ids"], dtype=np.int64))
258
+ phoneme_ids_lens.append(item["phoneme_ids_len"])
259
+ semantic_ids_lens.append(item["semantic_ids_len"])
260
+
261
+ # pad 0
262
+ phoneme_ids = batch_sequences(phoneme_ids)
263
+ semantic_ids = batch_sequences(semantic_ids, pad_value=self.PAD)
264
+
265
+ # # convert each batch to torch.tensor
266
+ phoneme_ids = torch.tensor(phoneme_ids)
267
+ semantic_ids = torch.tensor(semantic_ids)
268
+ phoneme_ids_lens = torch.tensor(phoneme_ids_lens)
269
+ semantic_ids_lens = torch.tensor(semantic_ids_lens)
270
+ bert_padded = torch.FloatTensor(len(examples), 1024, max(phoneme_ids_lens))
271
+ bert_padded.zero_()
272
+
273
+ for idx, item in enumerate(examples):
274
+ bert = item["bert_feature"]
275
+ if bert != None:
276
+ bert_padded[idx, :, : bert.shape[-1]] = bert
277
+
278
+ return {
279
+ # List[int]
280
+ "ids": sample_index,
281
+ # torch.Tensor (B, max_phoneme_length)
282
+ "phoneme_ids": phoneme_ids,
283
+ # torch.Tensor (B)
284
+ "phoneme_ids_len": phoneme_ids_lens,
285
+ # torch.Tensor (B, max_semantic_ids_length)
286
+ "semantic_ids": semantic_ids,
287
+ # torch.Tensor (B)
288
+ "semantic_ids_len": semantic_ids_lens,
289
+ # torch.Tensor (B, 1024, max_phoneme_length)
290
+ "bert_feature": bert_padded,
291
+ }
292
+
293
+
294
+ if __name__ == "__main__":
295
+ root_dir = "/data/docker/liujing04/gpt-vits/prepare/dump_mix/"
296
+ dataset = Text2SemanticDataset(
297
+ phoneme_path=root_dir + "phoneme_train.npy",
298
+ semantic_path=root_dir + "semantic_train.tsv",
299
+ )
300
+
301
+ batch_size = 12
302
+ dataloader = DataLoader(
303
+ dataset,
304
+ batch_size=batch_size,
305
+ collate_fn=dataset.collate,
306
+ shuffle=False,
307
+ )
308
+ for i, batch in enumerate(dataloader):
309
+ if i % 1000 == 0:
310
+ print(i)
311
+ # if i == 0:
312
+ # print('batch["ids"]:', batch["ids"])
313
+ # print('batch["phoneme_ids"]:', batch["phoneme_ids"],
314
+ # batch["phoneme_ids"].shape)
315
+ # print('batch["phoneme_ids_len"]:', batch["phoneme_ids_len"],
316
+ # batch["phoneme_ids_len"].shape)
317
+ # print('batch["semantic_ids"]:', batch["semantic_ids"],
318
+ # batch["semantic_ids"].shape)
319
+ # print('batch["semantic_ids_len"]:', batch["semantic_ids_len"],
320
+ # batch["semantic_ids_len"].shape)
GPT_SoVITS/AR/models/__init__.py ADDED
File without changes
GPT_SoVITS/AR/models/t2s_lightning_module.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_lightning_module.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import os
4
+ import sys
5
+
6
+ now_dir = os.getcwd()
7
+ sys.path.append(now_dir)
8
+ from typing import Dict
9
+
10
+ import torch
11
+ from pytorch_lightning import LightningModule
12
+
13
+ from AR.models.t2s_model import Text2SemanticDecoder
14
+ from AR.modules.lr_schedulers import WarmupCosineLRSchedule
15
+ from AR.modules.optim import ScaledAdam
16
+
17
+
18
+ class Text2SemanticLightningModule(LightningModule):
19
+ def __init__(self, config, output_dir, is_train=True):
20
+ super().__init__()
21
+ self.config = config
22
+ self.top_k = 3
23
+ self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
24
+ pretrained_s1 = config.get("pretrained_s1")
25
+ if pretrained_s1 and is_train:
26
+ # print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
27
+ print(
28
+ self.load_state_dict(
29
+ torch.load(
30
+ pretrained_s1,
31
+ map_location="cpu",
32
+ )["weight"],
33
+ )
34
+ )
35
+ if is_train:
36
+ self.automatic_optimization = False
37
+ self.save_hyperparameters()
38
+ self.eval_dir = output_dir / "eval"
39
+ self.eval_dir.mkdir(parents=True, exist_ok=True)
40
+
41
+ def training_step(self, batch: Dict, batch_idx: int):
42
+ opt = self.optimizers()
43
+ scheduler = self.lr_schedulers()
44
+ forward = self.model.forward if self.config["train"].get("if_dpo", False) == True else self.model.forward_old
45
+ loss, acc = forward(
46
+ batch["phoneme_ids"],
47
+ batch["phoneme_ids_len"],
48
+ batch["semantic_ids"],
49
+ batch["semantic_ids_len"],
50
+ batch["bert_feature"],
51
+ )
52
+ self.manual_backward(loss)
53
+ if batch_idx > 0 and batch_idx % 4 == 0:
54
+ opt.step()
55
+ opt.zero_grad()
56
+ scheduler.step()
57
+
58
+ self.log(
59
+ "total_loss",
60
+ loss,
61
+ on_step=True,
62
+ on_epoch=True,
63
+ prog_bar=True,
64
+ sync_dist=True,
65
+ )
66
+ self.log(
67
+ "lr",
68
+ scheduler.get_last_lr()[0],
69
+ on_epoch=True,
70
+ prog_bar=True,
71
+ sync_dist=True,
72
+ )
73
+ self.log(
74
+ f"top_{self.top_k}_acc",
75
+ acc,
76
+ on_step=True,
77
+ on_epoch=True,
78
+ prog_bar=True,
79
+ sync_dist=True,
80
+ )
81
+
82
+ def validation_step(self, batch: Dict, batch_idx: int):
83
+ return
84
+
85
+ # # get loss
86
+ # loss, acc = self.model.forward(
87
+ # batch['phoneme_ids'], batch['phoneme_ids_len'],
88
+ # batch['semantic_ids'], batch['semantic_ids_len'],
89
+ # batch['bert_feature']
90
+ # )
91
+ #
92
+ # self.log(
93
+ # "val_total_loss",
94
+ # loss,
95
+ # on_step=True,
96
+ # on_epoch=True,
97
+ # prog_bar=True,
98
+ # sync_dist=True)
99
+ # self.log(
100
+ # f"val_top_{self.top_k}_acc",
101
+ # acc,
102
+ # on_step=True,
103
+ # on_epoch=True,
104
+ # prog_bar=True,
105
+ # sync_dist=True)
106
+ #
107
+ # # get infer output
108
+ # semantic_len = batch['semantic_ids'].size(1)
109
+ # prompt_len = min(int(semantic_len * 0.5), 150)
110
+ # prompt = batch['semantic_ids'][:, :prompt_len]
111
+ # pred_semantic = self.model.infer(batch['phoneme_ids'],
112
+ # batch['phoneme_ids_len'], prompt,
113
+ # batch['bert_feature']
114
+ # )
115
+ # save_name = f'semantic_toks_{batch_idx}.pt'
116
+ # save_path = os.path.join(self.eval_dir, save_name)
117
+ # torch.save(pred_semantic.detach().cpu(), save_path)
118
+
119
+ def configure_optimizers(self):
120
+ model_parameters = self.model.parameters()
121
+ parameters_names = []
122
+ parameters_names.append([name_param_pair[0] for name_param_pair in self.model.named_parameters()])
123
+ lm_opt = ScaledAdam(
124
+ model_parameters,
125
+ lr=0.01,
126
+ betas=(0.9, 0.95),
127
+ clipping_scale=2.0,
128
+ parameters_names=parameters_names,
129
+ show_dominant_parameters=False,
130
+ clipping_update_period=1000,
131
+ )
132
+
133
+ return {
134
+ "optimizer": lm_opt,
135
+ "lr_scheduler": {
136
+ "scheduler": WarmupCosineLRSchedule(
137
+ lm_opt,
138
+ init_lr=self.config["optimizer"]["lr_init"],
139
+ peak_lr=self.config["optimizer"]["lr"],
140
+ end_lr=self.config["optimizer"]["lr_end"],
141
+ warmup_steps=self.config["optimizer"]["warmup_steps"],
142
+ total_steps=self.config["optimizer"]["decay_steps"],
143
+ )
144
+ },
145
+ }
GPT_SoVITS/AR/models/t2s_lightning_module_onnx.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_lightning_module.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import os
4
+ import sys
5
+
6
+ now_dir = os.getcwd()
7
+ sys.path.append(now_dir)
8
+ from typing import Dict
9
+
10
+ import torch
11
+ from pytorch_lightning import LightningModule
12
+
13
+ from AR.models.t2s_model_onnx import Text2SemanticDecoder
14
+ from AR.modules.lr_schedulers import WarmupCosineLRSchedule
15
+ from AR.modules.optim import ScaledAdam
16
+
17
+
18
+ class Text2SemanticLightningModule(LightningModule):
19
+ def __init__(self, config, output_dir, is_train=True):
20
+ super().__init__()
21
+ self.config = config
22
+ self.top_k = 3
23
+ self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
24
+ pretrained_s1 = config.get("pretrained_s1")
25
+ if pretrained_s1 and is_train:
26
+ # print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
27
+ print(
28
+ self.load_state_dict(
29
+ torch.load(
30
+ pretrained_s1,
31
+ map_location="cpu",
32
+ )["weight"],
33
+ ),
34
+ )
35
+ if is_train:
36
+ self.automatic_optimization = False
37
+ self.save_hyperparameters()
38
+ self.eval_dir = output_dir / "eval"
39
+ self.eval_dir.mkdir(parents=True, exist_ok=True)
40
+
41
+ def training_step(self, batch: Dict, batch_idx: int):
42
+ opt = self.optimizers()
43
+ scheduler = self.lr_schedulers()
44
+ loss, acc = self.model.forward(
45
+ batch["phoneme_ids"],
46
+ batch["phoneme_ids_len"],
47
+ batch["semantic_ids"],
48
+ batch["semantic_ids_len"],
49
+ batch["bert_feature"],
50
+ )
51
+ self.manual_backward(loss)
52
+ if batch_idx > 0 and batch_idx % 4 == 0:
53
+ opt.step()
54
+ opt.zero_grad()
55
+ scheduler.step()
56
+
57
+ self.log(
58
+ "total_loss",
59
+ loss,
60
+ on_step=True,
61
+ on_epoch=True,
62
+ prog_bar=True,
63
+ sync_dist=True,
64
+ )
65
+ self.log(
66
+ "lr",
67
+ scheduler.get_last_lr()[0],
68
+ on_epoch=True,
69
+ prog_bar=True,
70
+ sync_dist=True,
71
+ )
72
+ self.log(
73
+ f"top_{self.top_k}_acc",
74
+ acc,
75
+ on_step=True,
76
+ on_epoch=True,
77
+ prog_bar=True,
78
+ sync_dist=True,
79
+ )
80
+
81
+ def validation_step(self, batch: Dict, batch_idx: int):
82
+ return
83
+
84
+ def configure_optimizers(self):
85
+ model_parameters = self.model.parameters()
86
+ parameters_names = []
87
+ parameters_names.append([name_param_pair[0] for name_param_pair in self.model.named_parameters()])
88
+ lm_opt = ScaledAdam(
89
+ model_parameters,
90
+ lr=0.01,
91
+ betas=(0.9, 0.95),
92
+ clipping_scale=2.0,
93
+ parameters_names=parameters_names,
94
+ show_dominant_parameters=False,
95
+ clipping_update_period=1000,
96
+ )
97
+
98
+ return {
99
+ "optimizer": lm_opt,
100
+ "lr_scheduler": {
101
+ "scheduler": WarmupCosineLRSchedule(
102
+ lm_opt,
103
+ init_lr=self.config["optimizer"]["lr_init"],
104
+ peak_lr=self.config["optimizer"]["lr"],
105
+ end_lr=self.config["optimizer"]["lr_end"],
106
+ warmup_steps=self.config["optimizer"]["warmup_steps"],
107
+ total_steps=self.config["optimizer"]["decay_steps"],
108
+ )
109
+ },
110
+ }
GPT_SoVITS/AR/models/t2s_model.py ADDED
@@ -0,0 +1,935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_model.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import math
4
+ from typing import List, Optional
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+ from torchmetrics.classification import MulticlassAccuracy
10
+ from tqdm import tqdm
11
+
12
+ from AR.models.utils import (
13
+ dpo_loss,
14
+ get_batch_logps,
15
+ make_pad_mask,
16
+ make_pad_mask_left,
17
+ make_reject_y,
18
+ sample,
19
+ topk_sampling,
20
+ )
21
+ from AR.modules.embedding import SinePositionalEmbedding, TokenEmbedding
22
+ from AR.modules.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
23
+
24
+ default_config = {
25
+ "embedding_dim": 512,
26
+ "hidden_dim": 512,
27
+ "num_head": 8,
28
+ "num_layers": 12,
29
+ "num_codebook": 8,
30
+ "p_dropout": 0.0,
31
+ "vocab_size": 1024 + 1,
32
+ "phoneme_vocab_size": 512,
33
+ "EOS": 1024,
34
+ }
35
+
36
+
37
+ # @torch.jit.script ## 使用的话首次推理会非常慢,而且推理速度不稳定
38
+ # Efficient implementation equivalent to the following:
39
+ def scaled_dot_product_attention(
40
+ query: torch.Tensor,
41
+ key: torch.Tensor,
42
+ value: torch.Tensor,
43
+ attn_mask: Optional[torch.Tensor] = None,
44
+ scale: Optional[torch.Tensor] = None,
45
+ ) -> torch.Tensor:
46
+ B, H, L, S = query.size(0), query.size(1), query.size(-2), key.size(-2)
47
+ if scale is None:
48
+ scale_factor = torch.tensor(1 / math.sqrt(query.size(-1)))
49
+ else:
50
+ scale_factor = scale
51
+ attn_bias = torch.zeros(B, H, L, S, dtype=query.dtype, device=query.device)
52
+
53
+ if attn_mask is not None:
54
+ if attn_mask.dtype == torch.bool:
55
+ attn_bias.masked_fill_(attn_mask, float("-inf"))
56
+ else:
57
+ attn_bias += attn_mask
58
+ attn_weight = query @ key.transpose(-2, -1) * scale_factor
59
+ attn_weight += attn_bias
60
+ attn_weight = torch.softmax(attn_weight, dim=-1)
61
+
62
+ if attn_mask is not None:
63
+ if attn_mask.dtype == torch.bool:
64
+ attn_weight.masked_fill_(attn_mask, 0)
65
+ else:
66
+ attn_mask[attn_mask != float("-inf")] = 0
67
+ attn_mask[attn_mask == float("-inf")] = 1
68
+ attn_weight.masked_fill_(attn_mask, 0)
69
+
70
+ return attn_weight @ value
71
+
72
+
73
+ @torch.jit.script
74
+ class T2SMLP:
75
+ def __init__(self, w1, b1, w2, b2):
76
+ self.w1 = w1
77
+ self.b1 = b1
78
+ self.w2 = w2
79
+ self.b2 = b2
80
+
81
+ def forward(self, x):
82
+ x = F.relu(F.linear(x, self.w1, self.b1))
83
+ x = F.linear(x, self.w2, self.b2)
84
+ return x
85
+
86
+
87
+ @torch.jit.script
88
+ class T2SBlock:
89
+ def __init__(
90
+ self,
91
+ num_heads,
92
+ hidden_dim: int,
93
+ mlp: T2SMLP,
94
+ qkv_w,
95
+ qkv_b,
96
+ out_w,
97
+ out_b,
98
+ norm_w1,
99
+ norm_b1,
100
+ norm_eps1,
101
+ norm_w2,
102
+ norm_b2,
103
+ norm_eps2,
104
+ ):
105
+ self.num_heads = num_heads
106
+ self.mlp = mlp
107
+ self.hidden_dim: int = hidden_dim
108
+ self.qkv_w = qkv_w
109
+ self.qkv_b = qkv_b
110
+ self.out_w = out_w
111
+ self.out_b = out_b
112
+ self.norm_w1 = norm_w1
113
+ self.norm_b1 = norm_b1
114
+ self.norm_eps1 = norm_eps1
115
+ self.norm_w2 = norm_w2
116
+ self.norm_b2 = norm_b2
117
+ self.norm_eps2 = norm_eps2
118
+
119
+ self.false = torch.tensor(False, dtype=torch.bool)
120
+
121
+ @torch.jit.ignore
122
+ def to_mask(
123
+ self,
124
+ x: torch.Tensor,
125
+ padding_mask: Optional[torch.Tensor],
126
+ ):
127
+ if padding_mask is None:
128
+ return x
129
+
130
+ if padding_mask.dtype == torch.bool:
131
+ return x.masked_fill(padding_mask, 0)
132
+ else:
133
+ return x * padding_mask
134
+
135
+ def process_prompt(
136
+ self,
137
+ x: torch.Tensor,
138
+ attn_mask: torch.Tensor,
139
+ padding_mask: Optional[torch.Tensor] = None,
140
+ torch_sdpa: bool = True,
141
+ ):
142
+ q, k, v = F.linear(self.to_mask(x, padding_mask), self.qkv_w, self.qkv_b).chunk(3, dim=-1)
143
+
144
+ batch_size = q.shape[0]
145
+ q_len = q.shape[1]
146
+ kv_len = k.shape[1]
147
+
148
+ q = self.to_mask(q, padding_mask)
149
+ k_cache = self.to_mask(k, padding_mask)
150
+ v_cache = self.to_mask(v, padding_mask)
151
+
152
+ q = q.view(batch_size, q_len, self.num_heads, -1).transpose(1, 2)
153
+ k = k_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
154
+ v = v_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
155
+
156
+ if torch_sdpa:
157
+ attn = F.scaled_dot_product_attention(q, k, v, ~attn_mask)
158
+ else:
159
+ attn = scaled_dot_product_attention(q, k, v, attn_mask)
160
+
161
+ attn = attn.transpose(1, 2).reshape(batch_size, q_len, -1)
162
+ attn = F.linear(self.to_mask(attn, padding_mask), self.out_w, self.out_b)
163
+
164
+ x = x + attn
165
+ x = F.layer_norm(x, [self.hidden_dim], self.norm_w1, self.norm_b1, self.norm_eps1)
166
+ x = x + self.mlp.forward(x)
167
+ x = F.layer_norm(
168
+ x,
169
+ [self.hidden_dim],
170
+ self.norm_w2,
171
+ self.norm_b2,
172
+ self.norm_eps2,
173
+ )
174
+ return x, k_cache, v_cache
175
+
176
+ def decode_next_token(
177
+ self,
178
+ x: torch.Tensor,
179
+ k_cache: torch.Tensor,
180
+ v_cache: torch.Tensor,
181
+ attn_mask: torch.Tensor = None,
182
+ torch_sdpa: bool = True,
183
+ ):
184
+ q, k, v = F.linear(x, self.qkv_w, self.qkv_b).chunk(3, dim=-1)
185
+
186
+ k_cache = torch.cat([k_cache, k], dim=1)
187
+ v_cache = torch.cat([v_cache, v], dim=1)
188
+
189
+ batch_size = q.shape[0]
190
+ q_len = q.shape[1]
191
+ kv_len = k_cache.shape[1]
192
+
193
+ q = q.view(batch_size, q_len, self.num_heads, -1).transpose(1, 2)
194
+ k = k_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
195
+ v = v_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
196
+
197
+ if torch_sdpa:
198
+ attn = F.scaled_dot_product_attention(q, k, v, (~attn_mask) if attn_mask is not None else None)
199
+ else:
200
+ attn = scaled_dot_product_attention(q, k, v, attn_mask)
201
+
202
+ attn = attn.transpose(1, 2).reshape(batch_size, q_len, -1)
203
+ attn = F.linear(attn, self.out_w, self.out_b)
204
+
205
+ x = x + attn
206
+ x = F.layer_norm(
207
+ x,
208
+ [self.hidden_dim],
209
+ self.norm_w1,
210
+ self.norm_b1,
211
+ self.norm_eps1,
212
+ )
213
+ x = x + self.mlp.forward(x)
214
+ x = F.layer_norm(
215
+ x,
216
+ [self.hidden_dim],
217
+ self.norm_w2,
218
+ self.norm_b2,
219
+ self.norm_eps2,
220
+ )
221
+ return x, k_cache, v_cache
222
+
223
+
224
+ @torch.jit.script
225
+ class T2STransformer:
226
+ def __init__(self, num_blocks: int, blocks: List[T2SBlock]):
227
+ self.num_blocks: int = num_blocks
228
+ self.blocks = blocks
229
+
230
+ def process_prompt(
231
+ self,
232
+ x: torch.Tensor,
233
+ attn_mask: torch.Tensor,
234
+ padding_mask: Optional[torch.Tensor] = None,
235
+ torch_sdpa: bool = True,
236
+ ):
237
+ k_cache: List[torch.Tensor] = []
238
+ v_cache: List[torch.Tensor] = []
239
+ for i in range(self.num_blocks):
240
+ x, k_cache_, v_cache_ = self.blocks[i].process_prompt(x, attn_mask, padding_mask, torch_sdpa)
241
+ k_cache.append(k_cache_)
242
+ v_cache.append(v_cache_)
243
+ return x, k_cache, v_cache
244
+
245
+ def decode_next_token(
246
+ self,
247
+ x: torch.Tensor,
248
+ k_cache: List[torch.Tensor],
249
+ v_cache: List[torch.Tensor],
250
+ attn_mask: torch.Tensor = None,
251
+ torch_sdpa: bool = True,
252
+ ):
253
+ for i in range(self.num_blocks):
254
+ x, k_cache[i], v_cache[i] = self.blocks[i].decode_next_token(
255
+ x, k_cache[i], v_cache[i], attn_mask, torch_sdpa
256
+ )
257
+ return x, k_cache, v_cache
258
+
259
+
260
+ class Text2SemanticDecoder(nn.Module):
261
+ def __init__(self, config, norm_first=False, top_k=3):
262
+ super(Text2SemanticDecoder, self).__init__()
263
+ self.model_dim = config["model"]["hidden_dim"]
264
+ self.embedding_dim = config["model"]["embedding_dim"]
265
+ self.num_head = config["model"]["head"]
266
+ self.num_layers = config["model"]["n_layer"]
267
+ self.norm_first = norm_first
268
+ self.vocab_size = config["model"]["vocab_size"]
269
+ self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
270
+ self.p_dropout = config["model"]["dropout"]
271
+ self.EOS = config["model"]["EOS"]
272
+ self.norm_first = norm_first
273
+ assert self.EOS == self.vocab_size - 1
274
+ # should be same as num of kmeans bin
275
+ # assert self.EOS == 1024
276
+ self.bert_proj = nn.Linear(1024, self.embedding_dim)
277
+ self.ar_text_embedding = TokenEmbedding(
278
+ self.embedding_dim,
279
+ self.phoneme_vocab_size,
280
+ self.p_dropout,
281
+ )
282
+ self.ar_text_position = SinePositionalEmbedding(
283
+ self.embedding_dim,
284
+ dropout=0.1,
285
+ scale=False,
286
+ alpha=True,
287
+ )
288
+ self.ar_audio_embedding = TokenEmbedding(
289
+ self.embedding_dim,
290
+ self.vocab_size,
291
+ self.p_dropout,
292
+ )
293
+ self.ar_audio_position = SinePositionalEmbedding(
294
+ self.embedding_dim,
295
+ dropout=0.1,
296
+ scale=False,
297
+ alpha=True,
298
+ )
299
+
300
+ self.h = TransformerEncoder(
301
+ TransformerEncoderLayer(
302
+ d_model=self.model_dim,
303
+ nhead=self.num_head,
304
+ dim_feedforward=self.model_dim * 4,
305
+ dropout=0.1,
306
+ batch_first=True,
307
+ norm_first=norm_first,
308
+ ),
309
+ num_layers=self.num_layers,
310
+ norm=LayerNorm(self.model_dim) if norm_first else None,
311
+ )
312
+
313
+ self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
314
+ self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
315
+
316
+ self.ar_accuracy_metric = MulticlassAccuracy(
317
+ self.vocab_size,
318
+ top_k=top_k,
319
+ average="micro",
320
+ multidim_average="global",
321
+ ignore_index=self.EOS,
322
+ )
323
+
324
+ blocks = []
325
+
326
+ for i in range(self.num_layers):
327
+ layer = self.h.layers[i]
328
+ t2smlp = T2SMLP(
329
+ layer.linear1.weight,
330
+ layer.linear1.bias,
331
+ layer.linear2.weight,
332
+ layer.linear2.bias,
333
+ )
334
+
335
+ block = T2SBlock(
336
+ self.num_head,
337
+ self.model_dim,
338
+ t2smlp,
339
+ layer.self_attn.in_proj_weight,
340
+ layer.self_attn.in_proj_bias,
341
+ layer.self_attn.out_proj.weight,
342
+ layer.self_attn.out_proj.bias,
343
+ layer.norm1.weight,
344
+ layer.norm1.bias,
345
+ layer.norm1.eps,
346
+ layer.norm2.weight,
347
+ layer.norm2.bias,
348
+ layer.norm2.eps,
349
+ )
350
+
351
+ blocks.append(block)
352
+
353
+ self.t2s_transformer = T2STransformer(self.num_layers, blocks)
354
+
355
+ def make_input_data(self, x, x_lens, y, y_lens, bert_feature):
356
+ x = self.ar_text_embedding(x)
357
+ x = x + self.bert_proj(bert_feature.transpose(1, 2))
358
+ x = self.ar_text_position(x)
359
+ x_mask = make_pad_mask(x_lens)
360
+
361
+ y_mask = make_pad_mask(y_lens)
362
+ y_mask_int = y_mask.type(torch.int64)
363
+ codes = y.type(torch.int64) * (1 - y_mask_int)
364
+
365
+ # Training
366
+ # AR Decoder
367
+ y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
368
+ x_len = x_lens.max()
369
+ y_len = y_lens.max()
370
+ y_emb = self.ar_audio_embedding(y)
371
+ y_pos = self.ar_audio_position(y_emb)
372
+
373
+ xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
374
+
375
+ ar_xy_padding_mask = xy_padding_mask
376
+
377
+ x_attn_mask = F.pad(
378
+ torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
379
+ (0, y_len),
380
+ value=True,
381
+ )
382
+ # x_attn_mask[:, x_len]=False
383
+ y_attn_mask = F.pad(
384
+ torch.triu(
385
+ torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
386
+ diagonal=1,
387
+ ),
388
+ (x_len, 0),
389
+ value=False,
390
+ )
391
+
392
+ xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
393
+ bsz, src_len = x.shape[0], x_len + y_len
394
+ _xy_padding_mask = (
395
+ ar_xy_padding_mask.view(bsz, 1, 1, src_len)
396
+ .expand(-1, self.num_head, -1, -1)
397
+ .reshape(bsz * self.num_head, 1, src_len)
398
+ )
399
+ xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
400
+ new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
401
+ new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
402
+ xy_attn_mask = new_attn_mask
403
+ # x 和完整的 y 一次性输入模型
404
+ xy_pos = torch.concat([x, y_pos], dim=1)
405
+
406
+ return xy_pos, xy_attn_mask, targets
407
+
408
+ def forward(self, x, x_lens, y, y_lens, bert_feature):
409
+ """
410
+ x: phoneme_ids
411
+ y: semantic_ids
412
+ """
413
+
414
+ reject_y, reject_y_lens = make_reject_y(y, y_lens)
415
+
416
+ xy_pos, xy_attn_mask, targets = self.make_input_data(x, x_lens, y, y_lens, bert_feature)
417
+
418
+ xy_dec, _ = self.h(
419
+ (xy_pos, None),
420
+ mask=xy_attn_mask,
421
+ )
422
+ x_len = x_lens.max()
423
+ logits = self.ar_predict_layer(xy_dec[:, x_len:])
424
+
425
+ ###### DPO #############
426
+ reject_xy_pos, reject_xy_attn_mask, reject_targets = self.make_input_data(
427
+ x, x_lens, reject_y, reject_y_lens, bert_feature
428
+ )
429
+
430
+ reject_xy_dec, _ = self.h(
431
+ (reject_xy_pos, None),
432
+ mask=reject_xy_attn_mask,
433
+ )
434
+ x_len = x_lens.max()
435
+ reject_logits = self.ar_predict_layer(reject_xy_dec[:, x_len:])
436
+
437
+ # loss
438
+ # from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
439
+
440
+ loss_1 = F.cross_entropy(logits.permute(0, 2, 1), targets, reduction="sum")
441
+ acc = self.ar_accuracy_metric(logits.permute(0, 2, 1).detach(), targets).item()
442
+
443
+ A_logits, R_logits = get_batch_logps(logits, reject_logits, targets, reject_targets)
444
+ loss_2, _, _ = dpo_loss(A_logits, R_logits, 0, 0, 0.2, reference_free=True)
445
+
446
+ loss = loss_1 + loss_2
447
+
448
+ return loss, acc
449
+
450
+ def forward_old(self, x, x_lens, y, y_lens, bert_feature):
451
+ """
452
+ x: phoneme_ids
453
+ y: semantic_ids
454
+ """
455
+ x = self.ar_text_embedding(x)
456
+ x = x + self.bert_proj(bert_feature.transpose(1, 2))
457
+ x = self.ar_text_position(x)
458
+ x_mask = make_pad_mask(x_lens)
459
+
460
+ y_mask = make_pad_mask(y_lens)
461
+ y_mask_int = y_mask.type(torch.int64)
462
+ codes = y.type(torch.int64) * (1 - y_mask_int)
463
+
464
+ # Training
465
+ # AR Decoder
466
+ y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
467
+ x_len = x_lens.max()
468
+ y_len = y_lens.max()
469
+ y_emb = self.ar_audio_embedding(y)
470
+ y_pos = self.ar_audio_position(y_emb)
471
+
472
+ xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
473
+ ar_xy_padding_mask = xy_padding_mask
474
+
475
+ x_attn_mask = F.pad(
476
+ torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
477
+ (0, y_len),
478
+ value=True,
479
+ )
480
+ y_attn_mask = F.pad(
481
+ torch.triu(
482
+ torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
483
+ diagonal=1,
484
+ ),
485
+ (x_len, 0),
486
+ value=False,
487
+ )
488
+ xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
489
+ bsz, src_len = x.shape[0], x_len + y_len
490
+ _xy_padding_mask = (
491
+ ar_xy_padding_mask.view(bsz, 1, 1, src_len)
492
+ .expand(-1, self.num_head, -1, -1)
493
+ .reshape(bsz * self.num_head, 1, src_len)
494
+ )
495
+ xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
496
+ new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
497
+ new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
498
+ xy_attn_mask = new_attn_mask
499
+ # x 和完整的 y 一次性输入模型
500
+ xy_pos = torch.concat([x, y_pos], dim=1)
501
+ xy_dec, _ = self.h(
502
+ (xy_pos, None),
503
+ mask=xy_attn_mask,
504
+ )
505
+ logits = self.ar_predict_layer(xy_dec[:, x_len:]).permute(0, 2, 1)
506
+ # loss
507
+ # from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
508
+ loss = F.cross_entropy(logits, targets, reduction="sum")
509
+ acc = self.ar_accuracy_metric(logits.detach(), targets).item()
510
+ return loss, acc
511
+
512
+ # 需要看下这个函数和 forward 的区别以及没有 semantic 的时候 prompts 输入什么
513
+ def infer(
514
+ self,
515
+ x,
516
+ x_lens,
517
+ prompts,
518
+ bert_feature,
519
+ top_k: int = -100,
520
+ early_stop_num: int = -1,
521
+ temperature: float = 1.0,
522
+ ):
523
+ x = self.ar_text_embedding(x)
524
+ x = x + self.bert_proj(bert_feature.transpose(1, 2))
525
+ x = self.ar_text_position(x)
526
+
527
+ # AR Decoder
528
+ y = prompts
529
+ prefix_len = y.shape[1]
530
+ x_len = x.shape[1]
531
+ x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
532
+ stop = False
533
+ for _ in tqdm(range(1500)):
534
+ y_emb = self.ar_audio_embedding(y)
535
+ y_pos = self.ar_audio_position(y_emb)
536
+ # x 和逐渐增长的 y 一起输入给模型
537
+ xy_pos = torch.concat([x, y_pos], dim=1)
538
+ y_len = y.shape[1]
539
+ x_attn_mask_pad = F.pad(
540
+ x_attn_mask,
541
+ (0, y_len),
542
+ value=True,
543
+ )
544
+ y_attn_mask = F.pad(
545
+ torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
546
+ (x_len, 0),
547
+ value=False,
548
+ )
549
+ xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0).to(y.device)
550
+
551
+ xy_dec, _ = self.h(
552
+ (xy_pos, None),
553
+ mask=xy_attn_mask,
554
+ )
555
+ logits = self.ar_predict_layer(xy_dec[:, -1])
556
+ samples = topk_sampling(logits, top_k=top_k, top_p=1.0, temperature=temperature)
557
+
558
+ if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
559
+ print("use early stop num:", early_stop_num)
560
+ stop = True
561
+
562
+ if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
563
+ # print(torch.argmax(logits, dim=-1)[0] == self.EOS, samples[0, 0] == self.EOS)
564
+ stop = True
565
+ if stop:
566
+ if prompts.shape[1] == y.shape[1]:
567
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
568
+ print("bad zero prediction")
569
+ print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
570
+ break
571
+ # 本次生成的 semantic_ids 和之前的 y 构成新的 y
572
+ # print(samples.shape)#[1,1]#第一个1是bs
573
+ # import os
574
+ # os._exit(2333)
575
+ y = torch.concat([y, samples], dim=1)
576
+ return y
577
+
578
+ def pad_y_eos(self, y, y_mask_int, eos_id):
579
+ targets = F.pad(y, (0, 1), value=0) + eos_id * F.pad(y_mask_int, (0, 1), value=1)
580
+ # 错位
581
+ return targets[:, :-1], targets[:, 1:]
582
+
583
+ def infer_panel_batch_infer(
584
+ self,
585
+ x: List[torch.LongTensor], #####全部文本token
586
+ x_lens: torch.LongTensor,
587
+ prompts: torch.LongTensor, ####参考音频token
588
+ bert_feature: List[torch.LongTensor],
589
+ top_k: int = -100,
590
+ top_p: int = 100,
591
+ early_stop_num: int = -1,
592
+ temperature: float = 1.0,
593
+ repetition_penalty: float = 1.35,
594
+ **kwargs,
595
+ ):
596
+ if prompts is None:
597
+ print("Warning: Prompt free is not supported batch_infer! switch to naive_infer")
598
+ return self.infer_panel_naive_batched(
599
+ x,
600
+ x_lens,
601
+ prompts,
602
+ bert_feature,
603
+ top_k=top_k,
604
+ top_p=top_p,
605
+ early_stop_num=early_stop_num,
606
+ temperature=temperature,
607
+ **kwargs,
608
+ )
609
+
610
+ max_len = kwargs.get("max_len", x_lens.max())
611
+ x_list = []
612
+ for x_item, bert_item in zip(x, bert_feature):
613
+ # max_len = max(max_len, x_item.shape[0], bert_item.shape[1])
614
+ x_item = self.ar_text_embedding(x_item.unsqueeze(0))
615
+ x_item = x_item + self.bert_proj(bert_item.transpose(0, 1).unsqueeze(0))
616
+ x_item = self.ar_text_position(x_item).squeeze(0)
617
+ # x_item = F.pad(x_item,(0,0,0,max_len-x_item.shape[0]),value=0) if x_item.shape[0]<max_len else x_item ### padding right
618
+ x_item = (
619
+ F.pad(x_item, (0, 0, max_len - x_item.shape[0], 0), value=0) if x_item.shape[0] < max_len else x_item
620
+ ) ### padding left
621
+ x_list.append(x_item)
622
+ x: torch.Tensor = torch.stack(x_list, dim=0)
623
+
624
+ # AR Decoder
625
+ y = prompts
626
+
627
+ x_len = x.shape[1]
628
+ stop = False
629
+
630
+ k_cache = None
631
+ v_cache = None
632
+ ################### first step ##########################
633
+ assert y is not None, "Error: Prompt free is not supported batch_infer!"
634
+ ref_free = False
635
+
636
+ y_emb = self.ar_audio_embedding(y)
637
+ y_len = y_emb.shape[1]
638
+ prefix_len = y.shape[1]
639
+ y_lens = torch.LongTensor([y_emb.shape[1]] * y_emb.shape[0]).to(x.device)
640
+ y_pos = self.ar_audio_position(y_emb)
641
+ xy_pos = torch.concat([x, y_pos], dim=1)
642
+
643
+ ##### create mask #####
644
+ bsz = x.shape[0]
645
+ src_len = x_len + y_len
646
+ y_paddind_mask = make_pad_mask_left(y_lens, y_len)
647
+ x_paddind_mask = make_pad_mask_left(x_lens, max_len)
648
+
649
+ # (bsz, x_len + y_len)
650
+ padding_mask = torch.concat([x_paddind_mask, y_paddind_mask], dim=1)
651
+
652
+ x_mask = F.pad(
653
+ torch.zeros(x_len, x_len, dtype=torch.bool, device=x.device),
654
+ (0, y_len),
655
+ value=True,
656
+ )
657
+
658
+ y_mask = F.pad( ###yy的右上1扩展到左边xy的0,(y,x+y)
659
+ torch.triu(torch.ones(y_len, y_len, dtype=torch.bool, device=x.device), diagonal=1),
660
+ (x_len, 0),
661
+ value=False,
662
+ )
663
+
664
+ causal_mask = torch.concat([x_mask, y_mask], dim=0).view(1, src_len, src_len).repeat(bsz, 1, 1).to(x.device)
665
+ # padding_mask = padding_mask.unsqueeze(1) * padding_mask.unsqueeze(2) ### [b, x+y, x+y]
666
+ ### 上面是错误的,会导致padding的token被"看见"
667
+
668
+ # 正确的padding_mask应该是:
669
+ # | pad_len | x_len | y_len |
670
+ # [[PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
671
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
672
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6], 前3行按理说也应该被mask掉,但是为了防止计算attention时不出现nan,还是保留了,不影响结果
673
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
674
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
675
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
676
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
677
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6],
678
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6]]
679
+
680
+ padding_mask = padding_mask.view(bsz, 1, src_len).repeat(1, src_len, 1)
681
+
682
+ attn_mask: torch.Tensor = causal_mask.logical_or(padding_mask)
683
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, self.num_head, -1, -1).bool()
684
+
685
+ # 正确的attn_mask应该是这样的:
686
+ # | pad_len | x_len | y_len |
687
+ # [[PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS],
688
+ # [PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS],
689
+ # [PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS], 前3行按理说也应该被mask掉,但是为了防止计算attention时不出现nan,还是保留了,不影响结果
690
+ # [PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS],
691
+ # [PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS],
692
+ # [PAD, PAD, PAD, 1, 2, 3, EOS, EOS, EOS],
693
+ # [PAD, PAD, PAD, 1, 2, 3, 4, EOS, EOS],
694
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, EOS],
695
+ # [PAD, PAD, PAD, 1, 2, 3, 4, 5, 6]]
696
+
697
+ ###### decode #####
698
+ y_list = [None] * y.shape[0]
699
+ batch_idx_map = list(range(y.shape[0]))
700
+ idx_list = [None] * y.shape[0]
701
+ for idx in tqdm(range(1500)):
702
+ if idx == 0:
703
+ xy_dec, k_cache, v_cache = self.t2s_transformer.process_prompt(xy_pos, attn_mask, None)
704
+ else:
705
+ xy_dec, k_cache, v_cache = self.t2s_transformer.decode_next_token(xy_pos, k_cache, v_cache, attn_mask)
706
+ logits = self.ar_predict_layer(xy_dec[:, -1])
707
+
708
+ if idx == 0:
709
+ attn_mask = F.pad(attn_mask[:, :, -1].unsqueeze(-2), (0, 1), value=False)
710
+ logits = logits[:, :-1]
711
+ else:
712
+ attn_mask = F.pad(attn_mask, (0, 1), value=False)
713
+
714
+ samples = sample(
715
+ logits, y, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty, temperature=temperature
716
+ )[0]
717
+
718
+ y = torch.concat([y, samples], dim=1)
719
+
720
+ ####### 移除batch中已经生成完毕的序列,进一步优化计算量
721
+ tokens = torch.argmax(logits, dim=-1)
722
+ reserved_idx_of_batch_for_y = None
723
+ if (self.EOS in samples[:, 0]) or (self.EOS in tokens): ###如果生成到EOS,则停止
724
+ l1 = samples[:, 0] == self.EOS
725
+ l2 = tokens == self.EOS
726
+ l = l1.logical_or(l2)
727
+ removed_idx_of_batch_for_y = torch.where(l == True)[0].tolist()
728
+ reserved_idx_of_batch_for_y = torch.where(l == False)[0]
729
+ # batch_indexs = torch.tensor(batch_idx_map, device=y.device)[removed_idx_of_batch_for_y]
730
+ for i in removed_idx_of_batch_for_y:
731
+ batch_index = batch_idx_map[i]
732
+ idx_list[batch_index] = idx
733
+ y_list[batch_index] = y[i, :-1]
734
+
735
+ batch_idx_map = [batch_idx_map[i] for i in reserved_idx_of_batch_for_y.tolist()]
736
+
737
+ # 只保留batch中未生成完毕的序列
738
+ if reserved_idx_of_batch_for_y is not None:
739
+ # index = torch.LongTensor(batch_idx_map).to(y.device)
740
+ y = torch.index_select(y, dim=0, index=reserved_idx_of_batch_for_y)
741
+ attn_mask = torch.index_select(attn_mask, dim=0, index=reserved_idx_of_batch_for_y)
742
+ if k_cache is not None:
743
+ for i in range(len(k_cache)):
744
+ k_cache[i] = torch.index_select(k_cache[i], dim=0, index=reserved_idx_of_batch_for_y)
745
+ v_cache[i] = torch.index_select(v_cache[i], dim=0, index=reserved_idx_of_batch_for_y)
746
+
747
+ if (early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num) or idx == 1499:
748
+ print("use early stop num:", early_stop_num)
749
+ stop = True
750
+ for i, batch_index in enumerate(batch_idx_map):
751
+ batch_index = batch_idx_map[i]
752
+ idx_list[batch_index] = idx
753
+ y_list[batch_index] = y[i, :-1]
754
+
755
+ if None not in idx_list:
756
+ stop = True
757
+
758
+ if stop:
759
+ if y.shape[1] == 0:
760
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
761
+ print("bad zero prediction")
762
+ print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
763
+ break
764
+
765
+ ####################### update next step ###################################
766
+ y_emb = self.ar_audio_embedding(y[:, -1:])
767
+ xy_pos = y_emb * self.ar_audio_position.x_scale + self.ar_audio_position.alpha * self.ar_audio_position.pe[
768
+ :, y_len + idx
769
+ ].to(dtype=y_emb.dtype, device=y_emb.device)
770
+
771
+ if None in idx_list:
772
+ for i in range(x.shape[0]):
773
+ if idx_list[i] is None:
774
+ idx_list[i] = 1500 - 1 ###如果没有生成到EOS,就用最大长度代替
775
+
776
+ if ref_free:
777
+ return y_list, [0] * x.shape[0]
778
+ # print(idx_list)
779
+ return y_list, idx_list
780
+
781
+ def infer_panel_naive_batched(
782
+ self,
783
+ x: List[torch.LongTensor], #####全部文本token
784
+ x_lens: torch.LongTensor,
785
+ prompts: torch.LongTensor, ####参考音频token
786
+ bert_feature: List[torch.LongTensor],
787
+ top_k: int = -100,
788
+ top_p: int = 100,
789
+ early_stop_num: int = -1,
790
+ temperature: float = 1.0,
791
+ repetition_penalty: float = 1.35,
792
+ **kwargs,
793
+ ):
794
+ y_list = []
795
+ idx_list = []
796
+ for i in range(len(x)):
797
+ y, idx = self.infer_panel_naive(
798
+ x[i].unsqueeze(0),
799
+ x_lens[i],
800
+ prompts[i].unsqueeze(0) if prompts is not None else None,
801
+ bert_feature[i].unsqueeze(0),
802
+ top_k,
803
+ top_p,
804
+ early_stop_num,
805
+ temperature,
806
+ repetition_penalty,
807
+ **kwargs,
808
+ )
809
+ y_list.append(y[0])
810
+ idx_list.append(idx)
811
+
812
+ return y_list, idx_list
813
+
814
+ def infer_panel_naive(
815
+ self,
816
+ x: torch.LongTensor, #####全部文本token
817
+ x_lens: torch.LongTensor,
818
+ prompts: torch.LongTensor, ####参考音频token
819
+ bert_feature: torch.LongTensor,
820
+ top_k: int = -100,
821
+ top_p: int = 100,
822
+ early_stop_num: int = -1,
823
+ temperature: float = 1.0,
824
+ repetition_penalty: float = 1.35,
825
+ **kwargs,
826
+ ):
827
+ x = self.ar_text_embedding(x)
828
+ x = x + self.bert_proj(bert_feature.transpose(1, 2))
829
+ x = self.ar_text_position(x)
830
+
831
+ # AR Decoder
832
+ y = prompts
833
+
834
+ x_len = x.shape[1]
835
+ x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
836
+ stop = False
837
+ # print(1111111,self.num_layers)
838
+
839
+ k_cache = None
840
+ v_cache = None
841
+ ################### first step ##########################
842
+ if y is not None:
843
+ y_emb = self.ar_audio_embedding(y)
844
+ y_len = y_emb.shape[1]
845
+ prefix_len = y.shape[1]
846
+ y_pos = self.ar_audio_position(y_emb)
847
+ xy_pos = torch.concat([x, y_pos], dim=1)
848
+ ref_free = False
849
+ else:
850
+ y_emb = None
851
+ y_len = 0
852
+ prefix_len = 0
853
+ y_pos = None
854
+ xy_pos = x
855
+ y = torch.zeros(x.shape[0], 0, dtype=torch.int, device=x.device)
856
+ ref_free = True
857
+
858
+ bsz = x.shape[0]
859
+ src_len = x_len + y_len
860
+ x_attn_mask_pad = F.pad(
861
+ x_attn_mask,
862
+ (0, y_len), ###xx的纯0扩展到xx纯0+xy纯1,(x,x+y)
863
+ value=True,
864
+ )
865
+ y_attn_mask = F.pad( ###yy的右上1扩展到左边xy的0,(y,x+y)
866
+ torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
867
+ (x_len, 0),
868
+ value=False,
869
+ )
870
+ xy_attn_mask = (
871
+ torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
872
+ .unsqueeze(0)
873
+ .expand(bsz * self.num_head, -1, -1)
874
+ .view(bsz, self.num_head, src_len, src_len)
875
+ .to(device=x.device, dtype=torch.bool)
876
+ )
877
+
878
+ for idx in tqdm(range(1500)):
879
+ if xy_attn_mask is not None:
880
+ xy_dec, k_cache, v_cache = self.t2s_transformer.process_prompt(xy_pos, xy_attn_mask, None)
881
+ else:
882
+ xy_dec, k_cache, v_cache = self.t2s_transformer.decode_next_token(xy_pos, k_cache, v_cache)
883
+
884
+ logits = self.ar_predict_layer(xy_dec[:, -1])
885
+
886
+ if idx == 0:
887
+ xy_attn_mask = None
888
+ if idx < 11: ###至少预测出10个token不然不给停止(0.4s)
889
+ logits = logits[:, :-1]
890
+
891
+ samples = sample(
892
+ logits, y, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty, temperature=temperature
893
+ )[0]
894
+
895
+ y = torch.concat([y, samples], dim=1)
896
+
897
+ if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
898
+ print("use early stop num:", early_stop_num)
899
+ stop = True
900
+
901
+ if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
902
+ stop = True
903
+ if stop:
904
+ if y.shape[1] == 0:
905
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
906
+ print("bad zero prediction")
907
+ print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
908
+ break
909
+
910
+ ####################### update next step ###################################
911
+ y_emb = self.ar_audio_embedding(y[:, -1:])
912
+ xy_pos = y_emb * self.ar_audio_position.x_scale + self.ar_audio_position.alpha * self.ar_audio_position.pe[
913
+ :, y_len + idx
914
+ ].to(dtype=y_emb.dtype, device=y_emb.device)
915
+
916
+ if ref_free:
917
+ return y[:, :-1], 0
918
+ return y[:, :-1], idx
919
+
920
+ def infer_panel(
921
+ self,
922
+ x: torch.LongTensor, #####全部文本token
923
+ x_lens: torch.LongTensor,
924
+ prompts: torch.LongTensor, ####参考音频token
925
+ bert_feature: torch.LongTensor,
926
+ top_k: int = -100,
927
+ top_p: int = 100,
928
+ early_stop_num: int = -1,
929
+ temperature: float = 1.0,
930
+ repetition_penalty: float = 1.35,
931
+ **kwargs,
932
+ ):
933
+ return self.infer_panel_naive(
934
+ x, x_lens, prompts, bert_feature, top_k, top_p, early_stop_num, temperature, repetition_penalty, **kwargs
935
+ )
GPT_SoVITS/AR/models/t2s_model_onnx.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_model.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ from torchmetrics.classification import MulticlassAccuracy
7
+
8
+ from AR.modules.embedding_onnx import SinePositionalEmbedding, TokenEmbedding
9
+ from AR.modules.transformer_onnx import LayerNorm, TransformerEncoder, TransformerEncoderLayer
10
+
11
+ default_config = {
12
+ "embedding_dim": 512,
13
+ "hidden_dim": 512,
14
+ "num_head": 8,
15
+ "num_layers": 12,
16
+ "num_codebook": 8,
17
+ "p_dropout": 0.0,
18
+ "vocab_size": 1024 + 1,
19
+ "phoneme_vocab_size": 512,
20
+ "EOS": 1024,
21
+ }
22
+
23
+ inf_tensor_value = torch.FloatTensor([-float("Inf")]).float()
24
+
25
+
26
+ def logits_to_probs(
27
+ logits,
28
+ previous_tokens=None,
29
+ temperature: float = 1.0,
30
+ top_k=None,
31
+ top_p=None,
32
+ repetition_penalty: float = 1.0,
33
+ ):
34
+ previous_tokens = previous_tokens.squeeze()
35
+ if previous_tokens is not None and repetition_penalty != 1.0:
36
+ previous_tokens = previous_tokens.long()
37
+ score = torch.gather(logits, dim=0, index=previous_tokens)
38
+ score = torch.where(
39
+ score < 0,
40
+ score * repetition_penalty,
41
+ score / repetition_penalty,
42
+ )
43
+ logits.scatter_(dim=0, index=previous_tokens, src=score)
44
+
45
+ if top_p is not None and top_p < 1.0:
46
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
47
+ cum_probs = torch.cumsum(
48
+ torch.nn.functional.softmax(
49
+ sorted_logits,
50
+ dim=-1,
51
+ ),
52
+ dim=-1,
53
+ )
54
+ sorted_indices_to_remove = cum_probs > top_p
55
+ sorted_indices_to_remove[0] = False # keep at least one option
56
+ indices_to_remove = sorted_indices_to_remove.scatter(
57
+ dim=0,
58
+ index=sorted_indices,
59
+ src=sorted_indices_to_remove,
60
+ )
61
+ logits = logits.masked_fill(indices_to_remove, -float("Inf"))
62
+
63
+ logits = logits / max(temperature, 1e-5)
64
+
65
+ if top_k is not None:
66
+ v, _ = torch.topk(logits, top_k)
67
+ pivot = v.select(-1, -1).unsqueeze(-1)
68
+ logits = torch.where(logits < pivot, inf_tensor_value, logits)
69
+
70
+ probs = torch.nn.functional.softmax(logits, dim=-1)
71
+ return probs
72
+
73
+
74
+ def multinomial_sample_one_no_sync(
75
+ probs_sort,
76
+ ): # Does multinomial sampling without a cuda synchronization
77
+ q = torch.randn_like(probs_sort)
78
+ return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
79
+
80
+
81
+ def sample(
82
+ logits,
83
+ previous_tokens,
84
+ **sampling_kwargs,
85
+ ):
86
+ probs = logits_to_probs(
87
+ logits=logits,
88
+ previous_tokens=previous_tokens,
89
+ **sampling_kwargs,
90
+ )
91
+ idx_next = multinomial_sample_one_no_sync(probs)
92
+ return idx_next, probs
93
+
94
+
95
+ class OnnxEncoder(nn.Module):
96
+ def __init__(self, ar_text_embedding, bert_proj, ar_text_position):
97
+ super().__init__()
98
+ self.ar_text_embedding = ar_text_embedding
99
+ self.bert_proj = bert_proj
100
+ self.ar_text_position = ar_text_position
101
+
102
+ def forward(self, x, bert_feature):
103
+ x = self.ar_text_embedding(x)
104
+ x = x + self.bert_proj(bert_feature.transpose(1, 2))
105
+ return self.ar_text_position(x)
106
+
107
+
108
+ class T2SFirstStageDecoder(nn.Module):
109
+ def __init__(
110
+ self,
111
+ ar_audio_embedding,
112
+ ar_audio_position,
113
+ h,
114
+ ar_predict_layer,
115
+ loss_fct,
116
+ ar_accuracy_metric,
117
+ top_k,
118
+ early_stop_num,
119
+ num_layers,
120
+ ):
121
+ super().__init__()
122
+ self.ar_audio_embedding = ar_audio_embedding
123
+ self.ar_audio_position = ar_audio_position
124
+ self.h = h
125
+ self.ar_predict_layer = ar_predict_layer
126
+ self.loss_fct = loss_fct
127
+ self.ar_accuracy_metric = ar_accuracy_metric
128
+ self.top_k = top_k
129
+ self.early_stop_num = early_stop_num
130
+ self.num_layers = num_layers
131
+
132
+ def forward(self, x, prompt):
133
+ y = prompt
134
+ x_example = x[:, :, 0] * 0.0
135
+ # N, 1, 512
136
+ cache = {
137
+ "all_stage": self.num_layers,
138
+ "k": None,
139
+ "v": None,
140
+ "y_emb": None,
141
+ "first_infer": 1,
142
+ "stage": 0,
143
+ }
144
+
145
+ y_emb = self.ar_audio_embedding(y)
146
+
147
+ cache["y_emb"] = y_emb
148
+ y_pos = self.ar_audio_position(y_emb)
149
+
150
+ xy_pos = torch.concat([x, y_pos], dim=1)
151
+
152
+ y_example = y_pos[:, :, 0] * 0.0
153
+ x_attn_mask = torch.matmul(x_example.transpose(0, 1), x_example).bool()
154
+ y_attn_mask = torch.ones_like(torch.matmul(y_example.transpose(0, 1), y_example), dtype=torch.int64)
155
+ y_attn_mask = torch.cumsum(y_attn_mask, dim=1) - torch.cumsum(
156
+ torch.ones_like(
157
+ y_example.transpose(0, 1),
158
+ dtype=torch.int64,
159
+ ),
160
+ dim=0,
161
+ )
162
+ y_attn_mask = y_attn_mask > 0
163
+
164
+ x_y_pad = torch.matmul(x_example.transpose(0, 1), y_example).bool()
165
+ y_x_pad = torch.matmul(y_example.transpose(0, 1), x_example).bool()
166
+ x_attn_mask_pad = torch.cat([x_attn_mask, torch.ones_like(x_y_pad)], dim=1)
167
+ y_attn_mask = torch.cat([y_x_pad, y_attn_mask], dim=1)
168
+ xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
169
+ cache["k"] = (
170
+ torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))
171
+ .unsqueeze(1)
172
+ .repeat(self.num_layers, 1, 1, 1)
173
+ )
174
+ cache["v"] = (
175
+ torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))
176
+ .unsqueeze(1)
177
+ .repeat(self.num_layers, 1, 1, 1)
178
+ )
179
+
180
+ xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
181
+ logits = self.ar_predict_layer(xy_dec[:, -1])
182
+ samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
183
+
184
+ y = torch.concat([y, samples], dim=1)
185
+
186
+ return y, cache["k"], cache["v"], cache["y_emb"], x_example
187
+
188
+
189
+ class T2SStageDecoder(nn.Module):
190
+ def __init__(
191
+ self,
192
+ ar_audio_embedding,
193
+ ar_audio_position,
194
+ h,
195
+ ar_predict_layer,
196
+ loss_fct,
197
+ ar_accuracy_metric,
198
+ top_k,
199
+ early_stop_num,
200
+ num_layers,
201
+ ):
202
+ super().__init__()
203
+ self.ar_audio_embedding = ar_audio_embedding
204
+ self.ar_audio_position = ar_audio_position
205
+ self.h = h
206
+ self.ar_predict_layer = ar_predict_layer
207
+ self.loss_fct = loss_fct
208
+ self.ar_accuracy_metric = ar_accuracy_metric
209
+ self.top_k = top_k
210
+ self.early_stop_num = early_stop_num
211
+ self.num_layers = num_layers
212
+
213
+ def forward(self, y, k, v, y_emb, x_example):
214
+ cache = {
215
+ "all_stage": self.num_layers,
216
+ "k": torch.nn.functional.pad(k, (0, 0, 0, 0, 0, 1)),
217
+ "v": torch.nn.functional.pad(v, (0, 0, 0, 0, 0, 1)),
218
+ "y_emb": y_emb,
219
+ "first_infer": 0,
220
+ "stage": 0,
221
+ }
222
+
223
+ y_emb = torch.cat(
224
+ [
225
+ cache["y_emb"],
226
+ self.ar_audio_embedding(y[:, -1:]),
227
+ ],
228
+ 1,
229
+ )
230
+ cache["y_emb"] = y_emb
231
+ y_pos = self.ar_audio_position(y_emb)
232
+
233
+ xy_pos = y_pos[:, -1:]
234
+
235
+ y_example = y_pos[:, :, 0] * 0.0
236
+
237
+ xy_attn_mask = torch.cat([x_example, y_example], dim=1)
238
+ xy_attn_mask = torch.zeros_like(xy_attn_mask, dtype=torch.bool)
239
+
240
+ xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
241
+ logits = self.ar_predict_layer(xy_dec[:, -1])
242
+ samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
243
+
244
+ y = torch.concat([y, samples], dim=1)
245
+
246
+ return y, cache["k"], cache["v"], cache["y_emb"], logits, samples
247
+
248
+
249
+ class Text2SemanticDecoder(nn.Module):
250
+ def __init__(self, config, norm_first=False, top_k=3):
251
+ super(Text2SemanticDecoder, self).__init__()
252
+ self.model_dim = config["model"]["hidden_dim"]
253
+ self.embedding_dim = config["model"]["embedding_dim"]
254
+ self.num_head = config["model"]["head"]
255
+ self.num_layers = config["model"]["n_layer"]
256
+ self.norm_first = norm_first
257
+ self.vocab_size = config["model"]["vocab_size"]
258
+ self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
259
+ self.p_dropout = float(config["model"]["dropout"])
260
+ self.EOS = config["model"]["EOS"]
261
+ self.norm_first = norm_first
262
+ assert self.EOS == self.vocab_size - 1
263
+ self.bert_proj = nn.Linear(1024, self.embedding_dim)
264
+ self.ar_text_embedding = TokenEmbedding(self.embedding_dim, self.phoneme_vocab_size, self.p_dropout)
265
+ self.ar_text_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
266
+ self.ar_audio_embedding = TokenEmbedding(self.embedding_dim, self.vocab_size, self.p_dropout)
267
+ self.ar_audio_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
268
+ self.h = TransformerEncoder(
269
+ TransformerEncoderLayer(
270
+ d_model=self.model_dim,
271
+ nhead=self.num_head,
272
+ dim_feedforward=self.model_dim * 4,
273
+ dropout=0.1,
274
+ batch_first=True,
275
+ norm_first=norm_first,
276
+ ),
277
+ num_layers=self.num_layers,
278
+ norm=LayerNorm(self.model_dim) if norm_first else None,
279
+ )
280
+ self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
281
+ self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
282
+ self.ar_accuracy_metric = MulticlassAccuracy(
283
+ self.vocab_size,
284
+ top_k=top_k,
285
+ average="micro",
286
+ multidim_average="global",
287
+ ignore_index=self.EOS,
288
+ )
289
+ self.top_k = torch.LongTensor([1])
290
+ self.early_stop_num = torch.LongTensor([-1])
291
+
292
+ def init_onnx(self):
293
+ self.onnx_encoder = OnnxEncoder(self.ar_text_embedding, self.bert_proj, self.ar_text_position)
294
+ self.first_stage_decoder = T2SFirstStageDecoder(
295
+ self.ar_audio_embedding,
296
+ self.ar_audio_position,
297
+ self.h,
298
+ self.ar_predict_layer,
299
+ self.loss_fct,
300
+ self.ar_accuracy_metric,
301
+ self.top_k,
302
+ self.early_stop_num,
303
+ self.num_layers,
304
+ )
305
+ self.stage_decoder = T2SStageDecoder(
306
+ self.ar_audio_embedding,
307
+ self.ar_audio_position,
308
+ self.h,
309
+ self.ar_predict_layer,
310
+ self.loss_fct,
311
+ self.ar_accuracy_metric,
312
+ self.top_k,
313
+ self.early_stop_num,
314
+ self.num_layers,
315
+ )
316
+
317
+ def forward(self, x, prompts, bert_feature):
318
+ early_stop_num = self.early_stop_num
319
+ prefix_len = prompts.shape[1]
320
+
321
+ x = self.onnx_encoder(x, bert_feature)
322
+ y, k, v, y_emb, stage, x_example = self.first_stage_decoder(x, prompts)
323
+
324
+ stop = False
325
+ for idx in range(1, 1500):
326
+ enco = self.stage_decoder(y, k, v, y_emb, stage, x_example)
327
+ y, k, v, y_emb, stage, logits, samples = enco
328
+ if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
329
+ stop = True
330
+ if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
331
+ stop = True
332
+ if stop:
333
+ break
334
+ y[0, -1] = 0
335
+ return y, idx
336
+
337
+ def infer(self, x, prompts, bert_feature):
338
+ top_k = self.top_k
339
+ early_stop_num = self.early_stop_num
340
+
341
+ x = self.onnx_encoder(x, bert_feature)
342
+
343
+ y = prompts
344
+ prefix_len = y.shape[1]
345
+ x_len = x.shape[1]
346
+ x_example = x[:, :, 0] * 0.0
347
+ x_attn_mask = torch.matmul(x_example.transpose(0, 1), x_example)
348
+ x_attn_mask = torch.zeros_like(x_attn_mask, dtype=torch.bool)
349
+
350
+ stop = False
351
+ cache = {
352
+ "all_stage": self.num_layers,
353
+ "k": [None] * self.num_layers,
354
+ "v": [None] * self.num_layers,
355
+ "y_emb": None,
356
+ "first_infer": 1,
357
+ "stage": 0,
358
+ }
359
+ for idx in range(1500):
360
+ if cache["first_infer"] == 1:
361
+ y_emb = self.ar_audio_embedding(y)
362
+ else:
363
+ y_emb = torch.cat([cache["y_emb"], self.ar_audio_embedding(y[:, -1:])], 1)
364
+ cache["y_emb"] = y_emb
365
+ y_pos = self.ar_audio_position(y_emb)
366
+ if cache["first_infer"] == 1:
367
+ xy_pos = torch.concat([x, y_pos], dim=1)
368
+ else:
369
+ xy_pos = y_pos[:, -1:]
370
+ y_len = y_pos.shape[1]
371
+ if cache["first_infer"] == 1:
372
+ x_attn_mask_pad = F.pad(x_attn_mask, (0, y_len), value=True)
373
+ y_attn_mask = F.pad(
374
+ torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
375
+ (x_len, 0),
376
+ value=False,
377
+ )
378
+ xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
379
+ else:
380
+ xy_attn_mask = torch.zeros((1, x_len + y_len), dtype=torch.bool)
381
+ xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
382
+ logits = self.ar_predict_layer(xy_dec[:, -1])
383
+ samples = sample(logits[0], y, top_k=top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
384
+ if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
385
+ stop = True
386
+ if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
387
+ stop = True
388
+ if stop:
389
+ if prompts.shape[1] == y.shape[1]:
390
+ y = torch.concat([y, torch.zeros_like(samples)], dim=1)
391
+ break
392
+ y = torch.concat([y, samples], dim=1)
393
+ cache["first_infer"] = 0
394
+ return y, idx
GPT_SoVITS/AR/models/utils.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/utils.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ from typing import Tuple
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+
9
+ def sequence_mask(length, max_length=None):
10
+ if max_length is None:
11
+ max_length = length.max()
12
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
13
+ return x.unsqueeze(0) < length.unsqueeze(1)
14
+
15
+
16
+ def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
17
+ """
18
+ Args:
19
+ lengths:
20
+ A 1-D tensor containing sentence lengths.
21
+ max_len:
22
+ The length of masks.
23
+ Returns:
24
+ Return a 2-D bool tensor, where masked positions
25
+ are filled with `True` and non-masked positions are
26
+ filled with `False`.
27
+
28
+ #>>> lengths = torch.tensor([1, 3, 2, 5])
29
+ #>>> make_pad_mask(lengths)
30
+ tensor([[False, True, True, True, True],
31
+ [False, False, False, True, True],
32
+ [False, False, True, True, True],
33
+ [False, False, False, False, False]])
34
+ """
35
+ assert lengths.ndim == 1, lengths.ndim
36
+ max_len = max(max_len, lengths.max())
37
+ n = lengths.size(0)
38
+ seq_range = torch.arange(0, max_len, device=lengths.device)
39
+ expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)
40
+
41
+ return expaned_lengths >= lengths.unsqueeze(-1)
42
+
43
+
44
+ def make_pad_mask_left(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
45
+ """
46
+ Args:
47
+ lengths:
48
+ A 1-D tensor containing sentence lengths.
49
+ max_len:
50
+ The length of masks.
51
+ Returns:
52
+ Return a 2-D bool tensor, where masked positions
53
+ are filled with `True` and non-masked positions are
54
+ filled with `False`.
55
+
56
+ #>>> lengths = torch.tensor([1, 3, 2, 5])
57
+ #>>> make_pad_mask(lengths)
58
+ tensor(
59
+ [
60
+ [True, True, False],
61
+ [True, False, False],
62
+ [True, True, False],
63
+ ...
64
+ ]
65
+ )
66
+ """
67
+ assert lengths.ndim == 1, lengths.ndim
68
+ max_len = max(max_len, lengths.max())
69
+ n = lengths.size(0)
70
+ seq_range = torch.arange(0, max_len, device=lengths.device)
71
+ expaned_lengths = seq_range.unsqueeze(0).repeat(n, 1)
72
+ expaned_lengths -= (max_len - lengths).unsqueeze(-1)
73
+
74
+ return expaned_lengths < 0
75
+
76
+
77
+ # https://github.com/microsoft/unilm/blob/master/xtune/src/transformers/modeling_utils.py
78
+ def top_k_top_p_filtering(
79
+ logits,
80
+ top_k=0,
81
+ top_p=1.0,
82
+ filter_value=-float("Inf"),
83
+ min_tokens_to_keep=1,
84
+ ):
85
+ """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
86
+ Args:
87
+ logits: logits distribution shape (batch size, vocabulary size)
88
+ if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
89
+ if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
90
+ Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
91
+ Make sure we keep at least min_tokens_to_keep per batch example in the output
92
+ From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
93
+ """
94
+ if top_k > 0:
95
+ top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
96
+ # Remove all tokens with a probability less than the last token of the top-k
97
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
98
+ logits[indices_to_remove] = filter_value
99
+
100
+ if top_p < 1.0:
101
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
102
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
103
+
104
+ # Remove tokens with cumulative probability above the threshold (token with 0 are kept)
105
+ sorted_indices_to_remove = cumulative_probs > top_p
106
+ if min_tokens_to_keep > 1:
107
+ # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
108
+ sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
109
+ # Shift the indices to the right to keep also the first token above the threshold
110
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
111
+ sorted_indices_to_remove[..., 0] = 0
112
+
113
+ # scatter sorted tensors to original indexing
114
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
115
+ logits[indices_to_remove] = filter_value
116
+ return logits
117
+
118
+
119
+ def topk_sampling(logits, top_k=10, top_p=1.0, temperature=1.0):
120
+ # temperature: (`optional`) float
121
+ # The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.
122
+ # top_k: (`optional`) int
123
+ # The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.
124
+ # top_p: (`optional`) float
125
+ # The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.
126
+
127
+ # Temperature (higher temperature => more likely to sample low probability tokens)
128
+ if temperature != 1.0:
129
+ logits = logits / temperature
130
+ # Top-p/top-k filtering
131
+ logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
132
+ # Sample
133
+ token = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
134
+ return token
135
+
136
+
137
+ from typing import Optional
138
+
139
+
140
+ def multinomial_sample_one_no_sync(
141
+ probs_sort,
142
+ ): # Does multinomial sampling without a cuda synchronization
143
+ q = torch.empty_like(probs_sort).exponential_(1)
144
+ return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
145
+
146
+
147
+ def logits_to_probs(
148
+ logits,
149
+ previous_tokens: Optional[torch.Tensor] = None,
150
+ temperature: float = 1.0,
151
+ top_k: Optional[int] = None,
152
+ top_p: Optional[int] = None,
153
+ repetition_penalty: float = 1.0,
154
+ ):
155
+ # if previous_tokens is not None:
156
+ # previous_tokens = previous_tokens.squeeze()
157
+ # print(logits.shape,previous_tokens.shape)
158
+ # pdb.set_trace()
159
+ if previous_tokens is not None and repetition_penalty != 1.0:
160
+ previous_tokens = previous_tokens.long()
161
+ score = torch.gather(logits, dim=1, index=previous_tokens)
162
+ score = torch.where(
163
+ score < 0,
164
+ score * repetition_penalty,
165
+ score / repetition_penalty,
166
+ )
167
+ logits.scatter_(dim=1, index=previous_tokens, src=score)
168
+
169
+ if top_p is not None and top_p < 1.0:
170
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
171
+ cum_probs = torch.cumsum(torch.nn.functional.softmax(sorted_logits, dim=-1), dim=-1)
172
+ sorted_indices_to_remove = cum_probs > top_p
173
+ sorted_indices_to_remove[:, 0] = False # keep at least one option
174
+ indices_to_remove = sorted_indices_to_remove.scatter(
175
+ dim=1,
176
+ index=sorted_indices,
177
+ src=sorted_indices_to_remove,
178
+ )
179
+ logits = logits.masked_fill(indices_to_remove, -float("Inf"))
180
+
181
+ logits = logits / max(temperature, 1e-5)
182
+
183
+ if top_k is not None:
184
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
185
+ pivot = v[:, -1].unsqueeze(-1)
186
+ logits = torch.where(logits < pivot, -float("Inf"), logits)
187
+
188
+ probs = torch.nn.functional.softmax(logits, dim=-1)
189
+ return probs
190
+
191
+
192
+ def sample(
193
+ logits,
194
+ previous_tokens: Optional[torch.Tensor] = None,
195
+ **sampling_kwargs,
196
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
197
+ probs = logits_to_probs(logits=logits, previous_tokens=previous_tokens, **sampling_kwargs)
198
+ idx_next = multinomial_sample_one_no_sync(probs)
199
+ return idx_next, probs
200
+
201
+
202
+ def dpo_loss(
203
+ policy_chosen_logps: torch.FloatTensor,
204
+ policy_rejected_logps: torch.FloatTensor,
205
+ reference_chosen_logps: torch.FloatTensor,
206
+ reference_rejected_logps: torch.FloatTensor,
207
+ beta: float,
208
+ reference_free: bool = False,
209
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
210
+ pi_logratios = policy_chosen_logps - policy_rejected_logps
211
+ ref_logratios = reference_chosen_logps - reference_rejected_logps
212
+
213
+ if reference_free:
214
+ ref_logratios = 0
215
+
216
+ logits = pi_logratios - ref_logratios
217
+
218
+ losses = -F.logsigmoid(beta * logits)
219
+ chosen_rewards = beta * (policy_chosen_logps - reference_chosen_logps).detach()
220
+ rejected_rewards = beta * (policy_rejected_logps - reference_rejected_logps).detach()
221
+
222
+ return losses.mean(), chosen_rewards, rejected_rewards
223
+
224
+
225
+ def get_batch_logps(
226
+ logits_target: torch.FloatTensor,
227
+ logits_reject: torch.FloatTensor,
228
+ labels_target: torch.LongTensor,
229
+ labels_reject: torch.LongTensor,
230
+ average_log_prob: bool = False,
231
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
232
+ # dummy token; we'll ignore the losses on these tokens later
233
+
234
+ per_token_logps_target = torch.gather(
235
+ logits_target.log_softmax(-1), dim=2, index=labels_target.unsqueeze(2)
236
+ ).squeeze(2)
237
+ per_token_logps_reject = torch.gather(
238
+ logits_reject.log_softmax(-1), dim=2, index=labels_reject.unsqueeze(2)
239
+ ).squeeze(2)
240
+
241
+ return per_token_logps_target.sum(-1), per_token_logps_reject.sum(-1)
242
+
243
+
244
+ def make_reject_y(y_o, y_lens):
245
+ def repeat_P(y):
246
+ range_idx, _ = torch.randint(0, len(y), size=(2,)).sort()
247
+ pre = y[: range_idx[0]]
248
+ shf = y[range_idx[1] :]
249
+ range_text = y[range_idx[0] : range_idx[1]]
250
+ new_y = torch.cat([pre, range_text, range_text, shf])
251
+ return new_y
252
+
253
+ def lost_P(y):
254
+ range_idx, _ = torch.randint(0, len(y), size=(2,)).sort()
255
+ pre = y[: range_idx[0]]
256
+ shf = y[range_idx[1] :]
257
+ range_text = y[range_idx[0] : range_idx[1]]
258
+ new_y = torch.cat([pre, shf])
259
+ return new_y
260
+
261
+ bs = len(y_lens)
262
+ reject_y = []
263
+ reject_y_lens = []
264
+ for b in range(bs):
265
+ process_item_idx = torch.randint(0, 1, size=(1,))[0]
266
+ if process_item_idx == 0:
267
+ new_y = repeat_P(y_o[b])
268
+ reject_y.append(new_y)
269
+ reject_y_lens.append(len(new_y))
270
+ elif process_item_idx == 1:
271
+ new_y = lost_P(y_o[b])
272
+ reject_y.append(new_y)
273
+ reject_y_lens.append(len(new_y))
274
+ max_length = max(reject_y_lens)
275
+ for b in range(bs):
276
+ pad_length = max_length - reject_y_lens[b]
277
+ reject_y[b] = torch.cat([reject_y[b], torch.zeros(pad_length, dtype=y_o.dtype, device=y_o.device)], dim=0)
278
+
279
+ reject_y = torch.stack(reject_y, dim=0)
280
+ reject_y_lens = torch.tensor(reject_y_lens, device=y_lens.device)
281
+
282
+ return reject_y, reject_y_lens
GPT_SoVITS/AR/modules/__init__.py ADDED
File without changes
GPT_SoVITS/AR/modules/activation.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
2
+ from typing import Optional, Tuple
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn import Linear, Module
7
+ from torch.nn import functional as F
8
+ from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
9
+ from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
10
+ from torch.nn.parameter import Parameter
11
+
12
+ from AR.modules.patched_mha_with_cache import multi_head_attention_forward_patched
13
+
14
+ F.multi_head_attention_forward = multi_head_attention_forward_patched
15
+
16
+
17
+ class MultiheadAttention(Module):
18
+ r"""Allows the model to jointly attend to information
19
+ from different representation subspaces as described in the paper:
20
+ `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
21
+
22
+ Multi-Head Attention is defined as:
23
+
24
+ .. math::
25
+ \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
26
+
27
+ where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
28
+
29
+ ``forward()`` will use a special optimized implementation if all of the following
30
+ conditions are met:
31
+
32
+ - self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor. This
33
+ restriction will be loosened in the future.)
34
+ - Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
35
+ - training is disabled (using ``.eval()``)
36
+ - dropout is 0
37
+ - ``add_bias_kv`` is ``False``
38
+ - ``add_zero_attn`` is ``False``
39
+ - ``batch_first`` is ``True`` and the input is batched
40
+ - ``kdim`` and ``vdim`` are equal to ``embed_dim``
41
+ - at most one of ``key_padding_mask`` or ``attn_mask`` is passed
42
+ - if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
43
+ nor ``attn_mask`` is passed
44
+
45
+ If the optimized implementation is in use, a
46
+ `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
47
+ ``query``/``key``/``value`` to represent padding more efficiently than using a
48
+ padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
49
+ will be returned, and an additional speedup proportional to the fraction of the input
50
+ that is padding can be expected.
51
+
52
+ Args:
53
+ embed_dim: Total dimension of the model.
54
+ num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
55
+ across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
56
+ dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
57
+ bias: If specified, adds bias to input / output projection layers. Default: ``True``.
58
+ add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
59
+ add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
60
+ Default: ``False``.
61
+ kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
62
+ vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
63
+ batch_first: If ``True``, then the input and output tensors are provided
64
+ as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
65
+
66
+ Examples::
67
+
68
+ >>> # xdoctest: +SKIP
69
+ >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
70
+ >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
71
+
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,
93
+ ) -> None:
94
+ factory_kwargs = {"device": device, "dtype": dtype}
95
+ super(MultiheadAttention, self).__init__()
96
+ self.embed_dim = embed_dim
97
+ self.kdim = kdim if kdim is not None else embed_dim
98
+ self.vdim = vdim if vdim is not None else embed_dim
99
+ self._qkv_same_embed_dim = self.kdim == embed_dim and 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, "embed_dim must be divisible by num_heads"
106
+
107
+ if add_bias_kv:
108
+ self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
109
+ self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
110
+ else:
111
+ self.bias_k = self.bias_v = None
112
+
113
+ if linear1_cls == Linear:
114
+ if not self._qkv_same_embed_dim:
115
+ self.q_proj_weight = Parameter(
116
+ torch.empty((embed_dim, embed_dim), **factory_kwargs),
117
+ )
118
+ self.k_proj_weight = Parameter(
119
+ torch.empty((embed_dim, self.kdim), **factory_kwargs),
120
+ )
121
+ self.v_proj_weight = Parameter(
122
+ torch.empty((embed_dim, self.vdim), **factory_kwargs),
123
+ )
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
+ )
129
+ self.register_parameter("q_proj_weight", None)
130
+ self.register_parameter("k_proj_weight", None)
131
+ self.register_parameter("v_proj_weight", None)
132
+
133
+ if bias:
134
+ self.in_proj_bias = Parameter(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,
139
+ embed_dim,
140
+ bias=bias,
141
+ **factory_kwargs,
142
+ )
143
+
144
+ self._reset_parameters()
145
+ else:
146
+ if not self._qkv_same_embed_dim:
147
+ raise NotImplementedError
148
+ else:
149
+ self.in_proj_linear = linear1_cls(
150
+ embed_dim,
151
+ 3 * embed_dim,
152
+ bias=bias,
153
+ **factory_kwargs,
154
+ )
155
+ self.in_proj_weight = self.in_proj_linear.weight
156
+
157
+ self.register_parameter("q_proj_weight", None)
158
+ self.register_parameter("k_proj_weight", None)
159
+ self.register_parameter("v_proj_weight", None)
160
+
161
+ if bias:
162
+ self.in_proj_bias = self.in_proj_linear.bias
163
+ else:
164
+ self.register_parameter("in_proj_bias", None)
165
+
166
+ self.out_proj = linear2_cls(
167
+ embed_dim,
168
+ embed_dim,
169
+ bias=bias,
170
+ **factory_kwargs,
171
+ )
172
+
173
+ if self.bias_k is not None:
174
+ xavier_normal_(self.bias_k)
175
+ if self.bias_v is not None:
176
+ xavier_normal_(self.bias_v)
177
+
178
+ self.add_zero_attn = add_zero_attn
179
+
180
+ def _reset_parameters(self):
181
+ if self._qkv_same_embed_dim:
182
+ xavier_uniform_(self.in_proj_weight)
183
+ else:
184
+ xavier_uniform_(self.q_proj_weight)
185
+ xavier_uniform_(self.k_proj_weight)
186
+ xavier_uniform_(self.v_proj_weight)
187
+
188
+ if self.in_proj_bias is not None:
189
+ constant_(self.in_proj_bias, 0.0)
190
+ constant_(self.out_proj.bias, 0.0)
191
+
192
+ if self.bias_k is not None:
193
+ xavier_normal_(self.bias_k)
194
+ if self.bias_v is not None:
195
+ xavier_normal_(self.bias_v)
196
+
197
+ def __setstate__(self, state):
198
+ # Support loading old MultiheadAttention checkpoints generated by v1.1.0
199
+ if "_qkv_same_embed_dim" not in state:
200
+ state["_qkv_same_embed_dim"] = True
201
+
202
+ super(MultiheadAttention, self).__setstate__(state)
203
+
204
+ def forward(
205
+ self,
206
+ query: Tensor,
207
+ key: Tensor,
208
+ value: Tensor,
209
+ key_padding_mask: Optional[Tensor] = None,
210
+ need_weights: bool = True,
211
+ attn_mask: Optional[Tensor] = None,
212
+ average_attn_weights: bool = True,
213
+ cache=None,
214
+ ) -> Tuple[Tensor, Optional[Tensor]]:
215
+ r"""
216
+ Args:
217
+ query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
218
+ or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
219
+ :math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
220
+ Queries are compared against key-value pairs to produce the output.
221
+ See "Attention Is All You Need" for more details.
222
+ key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
223
+ or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
224
+ :math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
225
+ See "Attention Is All You Need" for more details.
226
+ value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
227
+ ``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
228
+ sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
229
+ See "Attention Is All You Need" for more details.
230
+ key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
231
+ to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
232
+ Binary and byte masks are supported.
233
+ For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
234
+ the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
235
+ need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
236
+ Default: ``True``.
237
+ attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
238
+ :math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
239
+ :math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
240
+ broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
241
+ Binary, byte, and float masks are supported. For a binary mask, a ``True`` value indicates that the
242
+ corresponding position is not allowed to attend. For a byte mask, a non-zero value indicates that the
243
+ corresponding position is not allowed to attend. For a float mask, the mask values will be added to
244
+ the attention weight.
245
+ average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
246
+ heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
247
+ effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
248
+
249
+ Outputs:
250
+ - **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
251
+ :math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
252
+ where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
253
+ embedding dimension ``embed_dim``.
254
+ - **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
255
+ returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
256
+ :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
257
+ :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
258
+ head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
259
+
260
+ .. note::
261
+ `batch_first` argument is ignored for unbatched inputs.
262
+ """
263
+ is_batched = query.dim() == 3
264
+ if key_padding_mask is not None:
265
+ _kpm_dtype = key_padding_mask.dtype
266
+ if _kpm_dtype != torch.bool and not torch.is_floating_point(
267
+ key_padding_mask,
268
+ ):
269
+ raise AssertionError("only bool and floating types of key_padding_mask are supported")
270
+ why_not_fast_path = ""
271
+ if not is_batched:
272
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
273
+ elif query is not key or key is not value:
274
+ # When lifting this restriction, don't forget to either
275
+ # enforce that the dtypes all match or test cases where
276
+ # they don't!
277
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
278
+ elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
279
+ why_not_fast_path = (
280
+ f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
281
+ )
282
+ elif self.in_proj_weight is not None and query.dtype != self.in_proj_weight.dtype:
283
+ # this case will fail anyway, but at least they'll get a useful error message.
284
+ why_not_fast_path = (
285
+ f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
286
+ )
287
+ elif self.training:
288
+ why_not_fast_path = "training is enabled"
289
+ elif not self.batch_first:
290
+ why_not_fast_path = "batch_first was not True"
291
+ elif self.bias_k is not None:
292
+ why_not_fast_path = "self.bias_k was not None"
293
+ elif self.bias_v is not None:
294
+ why_not_fast_path = "self.bias_v was not None"
295
+ elif self.dropout:
296
+ why_not_fast_path = f"dropout was {self.dropout}, required zero"
297
+ elif self.add_zero_attn:
298
+ why_not_fast_path = "add_zero_attn was enabled"
299
+ elif not self._qkv_same_embed_dim:
300
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
301
+ elif attn_mask is not None:
302
+ why_not_fast_path = "attn_mask was not None"
303
+ elif query.is_nested and key_padding_mask is not None:
304
+ why_not_fast_path = "key_padding_mask is not supported with NestedTensor input"
305
+ elif self.num_heads % 2 == 1:
306
+ why_not_fast_path = "num_heads is odd"
307
+ elif torch.is_autocast_enabled():
308
+ why_not_fast_path = "autocast is enabled"
309
+
310
+ if not why_not_fast_path:
311
+ tensor_args = (
312
+ query,
313
+ key,
314
+ value,
315
+ self.in_proj_weight,
316
+ self.in_proj_bias,
317
+ self.out_proj.weight,
318
+ self.out_proj.bias,
319
+ )
320
+ # We have to use list comprehensions below because TorchScript does not support
321
+ # generator expressions.
322
+ if torch.overrides.has_torch_function(tensor_args):
323
+ why_not_fast_path = "some Tensor argument has_torch_function"
324
+ elif not all([(x is None or x.is_cuda or "cpu" in str(x.device)) for x in tensor_args]):
325
+ why_not_fast_path = "some Tensor argument is neither CUDA nor CPU"
326
+ elif torch.is_grad_enabled() and any([x is not None and x.requires_grad for x in tensor_args]):
327
+ why_not_fast_path = "grad is enabled and at least one of query or the input/output projection weights or biases requires_grad"
328
+ if not why_not_fast_path:
329
+ return torch._native_multi_head_attention(
330
+ query,
331
+ key,
332
+ value,
333
+ self.embed_dim,
334
+ self.num_heads,
335
+ self.in_proj_weight,
336
+ self.in_proj_bias,
337
+ self.out_proj.weight,
338
+ self.out_proj.bias,
339
+ key_padding_mask if key_padding_mask is not None else attn_mask,
340
+ need_weights,
341
+ average_attn_weights,
342
+ 1 if key_padding_mask is not None else 0 if attn_mask is not None else None,
343
+ )
344
+
345
+ any_nested = query.is_nested or key.is_nested or value.is_nested
346
+ assert not any_nested, (
347
+ "MultiheadAttention does not support NestedTensor outside of its fast path. "
348
+ + f"The fast path was not hit because {why_not_fast_path}"
349
+ )
350
+
351
+ if self.batch_first and is_batched:
352
+ # make sure that the transpose op does not affect the "is" property
353
+ if key is value:
354
+ if query is key:
355
+ query = key = value = query.transpose(1, 0)
356
+ else:
357
+ query, key = [x.transpose(1, 0) for x in (query, key)]
358
+ value = key
359
+ else:
360
+ query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
361
+
362
+ if not self._qkv_same_embed_dim:
363
+ attn_output, attn_output_weights = F.multi_head_attention_forward(
364
+ query,
365
+ key,
366
+ value,
367
+ self.embed_dim,
368
+ self.num_heads,
369
+ self.in_proj_weight,
370
+ self.in_proj_bias,
371
+ self.bias_k,
372
+ self.bias_v,
373
+ self.add_zero_attn,
374
+ self.dropout,
375
+ self.out_proj.weight,
376
+ self.out_proj.bias,
377
+ training=self.training,
378
+ key_padding_mask=key_padding_mask,
379
+ need_weights=need_weights,
380
+ attn_mask=attn_mask,
381
+ use_separate_proj_weight=True,
382
+ q_proj_weight=self.q_proj_weight,
383
+ k_proj_weight=self.k_proj_weight,
384
+ v_proj_weight=self.v_proj_weight,
385
+ average_attn_weights=average_attn_weights,
386
+ cache=cache,
387
+ )
388
+ else:
389
+ attn_output, attn_output_weights = F.multi_head_attention_forward(
390
+ query,
391
+ key,
392
+ value,
393
+ self.embed_dim,
394
+ self.num_heads,
395
+ self.in_proj_weight,
396
+ self.in_proj_bias,
397
+ self.bias_k,
398
+ self.bias_v,
399
+ self.add_zero_attn,
400
+ self.dropout,
401
+ self.out_proj.weight,
402
+ self.out_proj.bias,
403
+ training=self.training,
404
+ key_padding_mask=key_padding_mask,
405
+ need_weights=need_weights,
406
+ attn_mask=attn_mask,
407
+ average_attn_weights=average_attn_weights,
408
+ cache=cache,
409
+ )
410
+ if self.batch_first and is_batched:
411
+ return attn_output.transpose(1, 0), attn_output_weights
412
+ else:
413
+ return attn_output, attn_output_weights
GPT_SoVITS/AR/modules/activation_onnx.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
2
+ from typing import Optional, Tuple
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn import Linear, Module
7
+ from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
8
+ from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
9
+ from torch.nn.parameter import Parameter
10
+
11
+ from AR.modules.patched_mha_with_cache_onnx import multi_head_attention_forward_patched
12
+
13
+
14
+ class MultiheadAttention(Module):
15
+ __constants__ = ["batch_first"]
16
+ bias_k: Optional[torch.Tensor]
17
+ bias_v: Optional[torch.Tensor]
18
+
19
+ def __init__(
20
+ self,
21
+ embed_dim,
22
+ num_heads,
23
+ dropout=0.0,
24
+ bias=True,
25
+ add_bias_kv=False,
26
+ add_zero_attn=False,
27
+ kdim=None,
28
+ vdim=None,
29
+ batch_first=False,
30
+ linear1_cls=Linear,
31
+ linear2_cls=Linear,
32
+ device=None,
33
+ dtype=None,
34
+ ) -> None:
35
+ factory_kwargs = {"device": device, "dtype": dtype}
36
+ super(MultiheadAttention, self).__init__()
37
+ self.embed_dim = embed_dim
38
+ self.kdim = kdim if kdim is not None else embed_dim
39
+ self.vdim = vdim if vdim is not None else embed_dim
40
+ self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
41
+
42
+ self.num_heads = num_heads
43
+ self.dropout = dropout
44
+ self.batch_first = batch_first
45
+ self.head_dim = embed_dim // num_heads
46
+ assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
47
+
48
+ if add_bias_kv:
49
+ self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
50
+ self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
51
+ else:
52
+ self.bias_k = self.bias_v = None
53
+
54
+ if linear1_cls == Linear:
55
+ if not self._qkv_same_embed_dim:
56
+ self.q_proj_weight = Parameter(
57
+ torch.empty(
58
+ (embed_dim, embed_dim),
59
+ **factory_kwargs,
60
+ )
61
+ )
62
+ self.k_proj_weight = Parameter(
63
+ torch.empty(
64
+ (embed_dim, self.kdim),
65
+ **factory_kwargs,
66
+ )
67
+ )
68
+ self.v_proj_weight = Parameter(
69
+ torch.empty(
70
+ (embed_dim, self.vdim),
71
+ **factory_kwargs,
72
+ )
73
+ )
74
+ self.register_parameter("in_proj_weight", None)
75
+ else:
76
+ self.in_proj_weight = Parameter(
77
+ torch.empty(
78
+ (3 * embed_dim, embed_dim),
79
+ **factory_kwargs,
80
+ )
81
+ )
82
+ self.register_parameter("q_proj_weight", None)
83
+ self.register_parameter("k_proj_weight", None)
84
+ self.register_parameter("v_proj_weight", None)
85
+
86
+ if bias:
87
+ self.in_proj_bias = Parameter(
88
+ torch.empty(3 * embed_dim, **factory_kwargs),
89
+ )
90
+ else:
91
+ self.register_parameter("in_proj_bias", None)
92
+ self.out_proj = NonDynamicallyQuantizableLinear(embed_dim, embed_dim, bias=bias, **factory_kwargs)
93
+
94
+ self._reset_parameters()
95
+ else:
96
+ if not self._qkv_same_embed_dim:
97
+ raise NotImplementedError
98
+ else:
99
+ self.in_proj_linear = linear1_cls(
100
+ embed_dim,
101
+ 3 * embed_dim,
102
+ bias=bias,
103
+ **factory_kwargs,
104
+ )
105
+ self.in_proj_weight = self.in_proj_linear.weight
106
+
107
+ self.register_parameter("q_proj_weight", None)
108
+ self.register_parameter("k_proj_weight", None)
109
+ self.register_parameter("v_proj_weight", None)
110
+
111
+ if bias:
112
+ self.in_proj_bias = self.in_proj_linear.bias
113
+ else:
114
+ self.register_parameter("in_proj_bias", None)
115
+
116
+ self.out_proj = linear2_cls(
117
+ embed_dim,
118
+ embed_dim,
119
+ bias=bias,
120
+ **factory_kwargs,
121
+ )
122
+
123
+ if self.bias_k is not None:
124
+ xavier_normal_(self.bias_k)
125
+ if self.bias_v is not None:
126
+ xavier_normal_(self.bias_v)
127
+
128
+ self.add_zero_attn = add_zero_attn
129
+
130
+ def _reset_parameters(self):
131
+ if self._qkv_same_embed_dim:
132
+ xavier_uniform_(self.in_proj_weight)
133
+ else:
134
+ xavier_uniform_(self.q_proj_weight)
135
+ xavier_uniform_(self.k_proj_weight)
136
+ xavier_uniform_(self.v_proj_weight)
137
+
138
+ if self.in_proj_bias is not None:
139
+ constant_(self.in_proj_bias, 0.0)
140
+ constant_(self.out_proj.bias, 0.0)
141
+
142
+ if self.bias_k is not None:
143
+ xavier_normal_(self.bias_k)
144
+ if self.bias_v is not None:
145
+ xavier_normal_(self.bias_v)
146
+
147
+ def __setstate__(self, state):
148
+ # Support loading old MultiheadAttention checkpoints generated by v1.1.0
149
+ if "_qkv_same_embed_dim" not in state:
150
+ state["_qkv_same_embed_dim"] = True
151
+
152
+ super(MultiheadAttention, self).__setstate__(state)
153
+
154
+ def forward(
155
+ self,
156
+ query: Tensor,
157
+ key: Tensor,
158
+ value: Tensor,
159
+ key_padding_mask: Optional[Tensor] = None,
160
+ need_weights: bool = True,
161
+ attn_mask: Optional[Tensor] = None,
162
+ average_attn_weights: bool = True,
163
+ cache=None,
164
+ ) -> Tuple[Tensor, Optional[Tensor]]:
165
+ any_nested = query.is_nested or key.is_nested or value.is_nested
166
+ query = key = value = query.transpose(1, 0)
167
+ attn_output = multi_head_attention_forward_patched(
168
+ query,
169
+ key,
170
+ value,
171
+ self.embed_dim,
172
+ self.num_heads,
173
+ self.in_proj_weight,
174
+ self.in_proj_bias,
175
+ self.bias_k,
176
+ self.bias_v,
177
+ self.add_zero_attn,
178
+ self.dropout,
179
+ self.out_proj.weight,
180
+ self.out_proj.bias,
181
+ training=self.training,
182
+ key_padding_mask=key_padding_mask,
183
+ need_weights=need_weights,
184
+ attn_mask=attn_mask,
185
+ average_attn_weights=average_attn_weights,
186
+ cache=cache,
187
+ )
188
+ return attn_output.transpose(1, 0)
GPT_SoVITS/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
+ ):
15
+ super().__init__()
16
+
17
+ self.vocab_size = vocab_size
18
+ self.embedding_dim = embedding_dim
19
+
20
+ self.dropout = torch.nn.Dropout(p=dropout)
21
+ self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
22
+
23
+ @property
24
+ def weight(self) -> torch.Tensor:
25
+ return self.word_embeddings.weight
26
+
27
+ def embedding(self, index: int) -> torch.Tensor:
28
+ return self.word_embeddings.weight[index : index + 1]
29
+
30
+ def forward(self, x: torch.Tensor):
31
+ x = self.word_embeddings(x)
32
+ x = self.dropout(x)
33
+ return x
34
+
35
+
36
+ class SinePositionalEmbedding(nn.Module):
37
+ def __init__(
38
+ self,
39
+ embedding_dim: int,
40
+ dropout: float = 0.0,
41
+ scale: bool = False,
42
+ alpha: bool = False,
43
+ ):
44
+ super().__init__()
45
+ self.embedding_dim = embedding_dim
46
+ self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
47
+ self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
48
+ self.dropout = torch.nn.Dropout(p=dropout)
49
+
50
+ self.reverse = False
51
+ self.pe = None
52
+ self.extend_pe(torch.tensor(0.0).expand(1, 4000))
53
+
54
+ def extend_pe(self, x):
55
+ """Reset the positional encodings."""
56
+ if self.pe is not None:
57
+ if self.pe.size(1) >= x.size(1):
58
+ if self.pe.dtype != x.dtype or self.pe.device != x.device:
59
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
60
+ return
61
+ pe = torch.zeros(x.size(1), self.embedding_dim)
62
+ if self.reverse:
63
+ position = torch.arange(x.size(1) - 1, -1, -1.0, dtype=torch.float32).unsqueeze(1)
64
+ else:
65
+ position = torch.arange(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) * -(math.log(10000.0) / self.embedding_dim)
68
+ )
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)
GPT_SoVITS/AR/modules/embedding_onnx.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ):
15
+ super().__init__()
16
+
17
+ self.vocab_size = vocab_size
18
+ self.embedding_dim = embedding_dim
19
+
20
+ self.dropout = torch.nn.Dropout(p=dropout)
21
+ self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
22
+
23
+ @property
24
+ def weight(self) -> torch.Tensor:
25
+ return self.word_embeddings.weight
26
+
27
+ def embedding(self, index: int) -> torch.Tensor:
28
+ return self.word_embeddings.weight[index : index + 1]
29
+
30
+ def forward(self, x: torch.Tensor):
31
+ x = self.word_embeddings(x)
32
+ x = self.dropout(x)
33
+ return x
34
+
35
+
36
+ class SinePositionalEmbedding(nn.Module):
37
+ def __init__(
38
+ self,
39
+ embedding_dim: int,
40
+ dropout: float = 0.0,
41
+ scale: bool = False,
42
+ alpha: bool = False,
43
+ ):
44
+ super().__init__()
45
+ self.embedding_dim = embedding_dim
46
+ self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
47
+ self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
48
+ self.dropout = torch.nn.Dropout(p=dropout)
49
+ self.reverse = False
50
+ self.div_term = torch.exp(torch.arange(0, self.embedding_dim, 2) * -(math.log(10000.0) / self.embedding_dim))
51
+
52
+ def extend_pe(self, x):
53
+ position = torch.cumsum(torch.ones_like(x[:, :, 0]), dim=1).transpose(0, 1)
54
+ scpe = (position * self.div_term).unsqueeze(0)
55
+ pe = torch.cat([torch.sin(scpe), torch.cos(scpe)]).permute(1, 2, 0)
56
+ pe = pe.contiguous().view(1, -1, self.embedding_dim)
57
+ return pe
58
+
59
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
60
+ pe = self.extend_pe(x)
61
+ output = x.unsqueeze(-1) if x.ndim == 2 else x
62
+ output = output * self.x_scale + self.alpha * pe
63
+ return self.dropout(output)
GPT_SoVITS/AR/modules/lr_schedulers.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/modules/lr_schedulers.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import math
4
+
5
+ import torch
6
+ from matplotlib import pyplot as plt
7
+ from torch import nn
8
+ from torch.optim import Adam
9
+
10
+
11
+ class WarmupCosineLRSchedule(torch.optim.lr_scheduler._LRScheduler):
12
+ """
13
+ Implements Warmup learning rate schedule until 'warmup_steps', going from 'init_lr' to 'peak_lr' for multiple optimizers.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ optimizer,
19
+ init_lr,
20
+ peak_lr,
21
+ end_lr,
22
+ warmup_steps=10000,
23
+ total_steps=400000,
24
+ current_step=0,
25
+ ):
26
+ self.init_lr = init_lr
27
+ self.peak_lr = peak_lr
28
+ self.end_lr = end_lr
29
+ self.optimizer = optimizer
30
+ self._warmup_rate = (peak_lr - init_lr) / warmup_steps
31
+ self._decay_rate = (end_lr - peak_lr) / (total_steps - warmup_steps)
32
+ self._current_step = current_step
33
+ self.lr = init_lr
34
+ self.warmup_steps = warmup_steps
35
+ self.total_steps = total_steps
36
+ self._last_lr = [self.lr]
37
+
38
+ def set_lr(self, lr):
39
+ self._last_lr = [g["lr"] for g in self.optimizer.param_groups]
40
+ for g in self.optimizer.param_groups:
41
+ # g['lr'] = lr
42
+ g["lr"] = self.end_lr ###锁定用线性
43
+
44
+ def step(self):
45
+ if self._current_step < self.warmup_steps:
46
+ lr = self.init_lr + self._warmup_rate * self._current_step
47
+
48
+ elif self._current_step > self.total_steps:
49
+ lr = self.end_lr
50
+
51
+ else:
52
+ decay_ratio = (self._current_step - self.warmup_steps) / (self.total_steps - self.warmup_steps)
53
+ if decay_ratio < 0.0 or decay_ratio > 1.0:
54
+ raise RuntimeError("Decay ratio must be in [0.0, 1.0]. Fix LR scheduler settings.")
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
+ if __name__ == "__main__":
66
+ m = nn.Linear(10, 10)
67
+ opt = Adam(m.parameters(), lr=1e-4)
68
+ s = WarmupCosineLRSchedule(
69
+ opt,
70
+ 1e-6,
71
+ 2e-4,
72
+ 1e-6,
73
+ warmup_steps=2000,
74
+ total_steps=20000,
75
+ current_step=0,
76
+ )
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()
GPT_SoVITS/AR/modules/optim.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Tuple
20
+
21
+ import torch
22
+ from torch import Tensor
23
+ from torch.optim import Optimizer
24
+
25
+
26
+ class BatchedOptimizer(Optimizer):
27
+ """
28
+ This class adds to class Optimizer the capability to optimize parameters in batches:
29
+ it will stack the parameters and their grads for you so the optimizer can work
30
+ on tensors with an extra leading dimension. This is intended for speed with GPUs,
31
+ as it reduces the number of kernels launched in the optimizer.
32
+
33
+ Args:
34
+ params:
35
+ """
36
+
37
+ def __init__(self, params, defaults):
38
+ super(BatchedOptimizer, self).__init__(params, defaults)
39
+
40
+ @contextlib.contextmanager
41
+ def batched_params(self, param_group, group_params_names):
42
+ """
43
+ This function returns (technically, yields) a list of
44
+ of tuples (p, state), where
45
+ p is a `fake` parameter that is stacked (over axis 0) from real parameters
46
+ that share the same shape, and its gradient is also stacked;
47
+ `state` is the state corresponding to this batch of parameters
48
+ (it will be physically located in the "state" for one of the real
49
+ parameters, the last one that has any particular shape and dtype).
50
+
51
+ This function is decorated as a context manager so that it can
52
+ write parameters back to their "real" locations.
53
+
54
+ The idea is, instead of doing:
55
+ <code>
56
+ for p in group["params"]:
57
+ state = self.state[p]
58
+ ...
59
+ </code>
60
+ you can do:
61
+ <code>
62
+ with self.batched_params(group["params"]) as batches:
63
+ for p, state, p_names in batches:
64
+ ...
65
+ </code>
66
+
67
+ Args:
68
+ group: a parameter group, which is a list of parameters; should be
69
+ one of self.param_groups.
70
+ group_params_names: name for each parameter in group,
71
+ which is List[str].
72
+ """
73
+ batches = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of nn.Parameter
74
+ batches_names = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of str
75
+
76
+ assert len(param_group) == len(group_params_names)
77
+ for p, named_p in zip(param_group, group_params_names):
78
+ key = (str(p.dtype), *p.shape)
79
+ batches[key].append(p)
80
+ batches_names[key].append(named_p)
81
+
82
+ batches_names_keys = list(batches_names.keys())
83
+ sorted_idx = sorted(range(len(batches_names)), key=lambda i: batches_names_keys[i])
84
+ batches_names = [batches_names[batches_names_keys[idx]] for idx in sorted_idx]
85
+ batches = [batches[batches_names_keys[idx]] for idx in sorted_idx]
86
+
87
+ stacked_params_dict = dict()
88
+
89
+ # turn batches into a list, in deterministic order.
90
+ # tuples will contain tuples of (stacked_param, state, stacked_params_names),
91
+ # one for each batch in `batches`.
92
+ tuples = []
93
+
94
+ for batch, batch_names in zip(batches, batches_names):
95
+ p = batch[0]
96
+ # we arbitrarily store the state in the
97
+ # state corresponding to the 1st parameter in the
98
+ # group. class Optimizer will take care of saving/loading state.
99
+ state = self.state[p]
100
+ p_stacked = torch.stack(batch)
101
+ grad = torch.stack([torch.zeros_like(p) if p.grad is None else p.grad for p in batch])
102
+ p_stacked.grad = grad
103
+ stacked_params_dict[key] = p_stacked
104
+ tuples.append((p_stacked, state, batch_names))
105
+
106
+ yield tuples # <-- calling code will do the actual optimization here!
107
+
108
+ for (stacked_params, _state, _names), batch in zip(tuples, batches):
109
+ for i, p in enumerate(batch): # batch is list of Parameter
110
+ p.copy_(stacked_params[i])
111
+
112
+
113
+ class ScaledAdam(BatchedOptimizer):
114
+ """
115
+ Implements 'Scaled Adam', a variant of Adam where we scale each parameter's update
116
+ proportional to the norm of that parameter; and also learn the scale of the parameter,
117
+ in log space, subject to upper and lower limits (as if we had factored each parameter as
118
+ param = underlying_param * log_scale.exp())
119
+
120
+
121
+ Args:
122
+ params: The parameters or param_groups to optimize (like other Optimizer subclasses)
123
+ lr: The learning rate. We will typically use a learning rate schedule that starts
124
+ at 0.03 and decreases over time, i.e. much higher than other common
125
+ optimizers.
126
+ clipping_scale: (e.g. 2.0)
127
+ A scale for gradient-clipping: if specified, the normalized gradients
128
+ over the whole model will be clipped to have 2-norm equal to
129
+ `clipping_scale` times the median 2-norm over the most recent period
130
+ of `clipping_update_period` minibatches. By "normalized gradients",
131
+ we mean after multiplying by the rms parameter value for this tensor
132
+ [for non-scalars]; this is appropriate because our update is scaled
133
+ by this quantity.
134
+ betas: beta1,beta2 are momentum constants for regular momentum, and moving sum-sq grad.
135
+ Must satisfy 0 < beta <= beta2 < 1.
136
+ scalar_lr_scale: A scaling factor on the learning rate, that we use to update the
137
+ scale of each parameter tensor and scalar parameters of the mode..
138
+ If each parameter were decomposed
139
+ as p * p_scale.exp(), where (p**2).mean().sqrt() == 1.0, scalar_lr_scale
140
+ would be a the scaling factor on the learning rate of p_scale.
141
+ eps: A general-purpose epsilon to prevent division by zero
142
+ param_min_rms: Minimum root-mean-square value of parameter tensor, for purposes of
143
+ learning the scale on the parameters (we'll constrain the rms of each non-scalar
144
+ parameter tensor to be >= this value)
145
+ param_max_rms: Maximum root-mean-square value of parameter tensor, for purposes of
146
+ learning the scale on the parameters (we'll constrain the rms of each non-scalar
147
+ parameter tensor to be <= this value)
148
+ scalar_max: Maximum absolute value for scalar parameters (applicable if your
149
+ model has any parameters with numel() == 1).
150
+ size_update_period: The periodicity, in steps, with which we update the size (scale)
151
+ of the parameter tensor. This is provided to save a little time
152
+ in the update.
153
+ clipping_update_period: if clipping_scale is specified, this is the period
154
+ """
155
+
156
+ def __init__(
157
+ self,
158
+ params,
159
+ lr=3e-02,
160
+ clipping_scale=None,
161
+ betas=(0.9, 0.98),
162
+ scalar_lr_scale=0.1,
163
+ eps=1.0e-08,
164
+ param_min_rms=1.0e-05,
165
+ param_max_rms=3.0,
166
+ scalar_max=10.0,
167
+ size_update_period=4,
168
+ clipping_update_period=100,
169
+ parameters_names=None,
170
+ show_dominant_parameters=True,
171
+ ):
172
+ assert parameters_names is not None, (
173
+ "Please prepare parameters_names,which is a List[List[str]]. Each List[str] is for a groupand each str is for a parameter"
174
+ )
175
+ defaults = dict(
176
+ lr=lr,
177
+ clipping_scale=clipping_scale,
178
+ betas=betas,
179
+ scalar_lr_scale=scalar_lr_scale,
180
+ eps=eps,
181
+ param_min_rms=param_min_rms,
182
+ param_max_rms=param_max_rms,
183
+ scalar_max=scalar_max,
184
+ size_update_period=size_update_period,
185
+ clipping_update_period=clipping_update_period,
186
+ )
187
+
188
+ super(ScaledAdam, self).__init__(params, defaults)
189
+ assert len(self.param_groups) == len(parameters_names)
190
+ self.parameters_names = parameters_names
191
+ self.show_dominant_parameters = show_dominant_parameters
192
+
193
+ def __setstate__(self, state):
194
+ super(ScaledAdam, self).__setstate__(state)
195
+
196
+ @torch.no_grad()
197
+ def step(self, closure=None):
198
+ """Performs a single optimization step.
199
+
200
+ Arguments:
201
+ closure (callable, optional): A closure that reevaluates the model
202
+ and returns the loss.
203
+ """
204
+ loss = None
205
+ if closure is not None:
206
+ with torch.enable_grad():
207
+ loss = closure()
208
+
209
+ batch = True
210
+
211
+ for group, group_params_names in zip(self.param_groups, self.parameters_names):
212
+ with self.batched_params(group["params"], group_params_names) as batches:
213
+ # batches is list of pairs (stacked_param, state). stacked_param is like
214
+ # a regular parameter, and will have a .grad, but the 1st dim corresponds to
215
+ # a stacking dim, it is not a real dim.
216
+
217
+ if len(batches[0][1]) == 0: # if len(first state) == 0: not yet initialized
218
+ clipping_scale = 1
219
+ else:
220
+ clipping_scale = self._get_clipping_scale(group, batches)
221
+
222
+ for p, state, _ in batches:
223
+ # Perform optimization step.
224
+ # grad is not going to be None, we handled that when creating the batches.
225
+ grad = p.grad
226
+ if grad.is_sparse:
227
+ raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
228
+ # State initialization
229
+ if len(state) == 0:
230
+ self._init_state(group, p, state)
231
+
232
+ self._step_one_batch(group, p, state, clipping_scale)
233
+
234
+ return loss
235
+
236
+ def _init_state(self, group: dict, p: Tensor, state: dict):
237
+ """
238
+ Initializes state dict for parameter 'p'. Assumes that dim 0 of tensor p
239
+ is actually the batch dimension, corresponding to batched-together
240
+ parameters of a given shape.
241
+
242
+
243
+ Args:
244
+ group: Dict to look up configuration values.
245
+ p: The parameter that we are initializing the state for
246
+ state: Dict from string to whatever state we are initializing
247
+ """
248
+ size_update_period = group["size_update_period"]
249
+
250
+ state["step"] = 0
251
+
252
+ kwargs = {"device": p.device, "dtype": p.dtype}
253
+
254
+ # 'delta' implements conventional momentum. There are
255
+ # several different kinds of update going on, so rather than
256
+ # compute "exp_avg" like in Adam, we store and decay a
257
+ # parameter-change "delta", which combines all forms of
258
+ # update. this is equivalent to how it's done in Adam,
259
+ # except for the first few steps.
260
+ state["delta"] = torch.zeros_like(p, memory_format=torch.preserve_format)
261
+
262
+ batch_size = p.shape[0]
263
+ numel = p.numel() // batch_size
264
+ numel = p.numel()
265
+
266
+ if numel > 1:
267
+ # "param_rms" just periodically records the scalar root-mean-square value of
268
+ # the parameter tensor.
269
+ # it has a shape like (batch_size, 1, 1, 1, 1)
270
+ param_rms = (p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt()
271
+ state["param_rms"] = param_rms
272
+
273
+ state["scale_exp_avg_sq"] = torch.zeros_like(param_rms)
274
+ state["scale_grads"] = torch.zeros(size_update_period, *param_rms.shape, **kwargs)
275
+
276
+ # exp_avg_sq is the weighted sum of scaled gradients. as in Adam.
277
+ state["exp_avg_sq"] = torch.zeros_like(p, memory_format=torch.preserve_format)
278
+
279
+ def _get_clipping_scale(self, group: dict, tuples: List[Tuple[Tensor, dict, List[str]]]) -> float:
280
+ """
281
+ Returns a scalar factor <= 1.0 that dictates gradient clipping, i.e. we will scale the gradients
282
+ by this amount before applying the rest of the update.
283
+
284
+ Args:
285
+ group: the parameter group, an item in self.param_groups
286
+ tuples: a list of tuples of (param, state, param_names)
287
+ where param is a batched set of parameters,
288
+ with a .grad (1st dim is batch dim)
289
+ and state is the state-dict where optimization parameters are kept.
290
+ param_names is a List[str] while each str is name for a parameter
291
+ in batched set of parameters "param".
292
+ """
293
+ assert len(tuples) >= 1
294
+ clipping_scale = group["clipping_scale"]
295
+ (first_p, first_state, _) = tuples[0]
296
+ step = first_state["step"]
297
+ if clipping_scale is None or step == 0:
298
+ # no clipping. return early on step == 0 because the other
299
+ # parameters' state won't have been initialized yet.
300
+ return 1.0
301
+ clipping_update_period = group["clipping_update_period"]
302
+
303
+ tot_sumsq = torch.tensor(0.0, device=first_p.device)
304
+ for p, state, param_names in tuples:
305
+ grad = p.grad
306
+ if grad.is_sparse:
307
+ raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
308
+ if p.numel() == p.shape[0]: # a batch of scalars
309
+ tot_sumsq += (grad**2).sum() # sum() to change shape [1] to []
310
+ else:
311
+ tot_sumsq += ((grad * state["param_rms"]) ** 2).sum()
312
+
313
+ tot_norm = tot_sumsq.sqrt()
314
+ if "model_norms" not in first_state:
315
+ first_state["model_norms"] = torch.zeros(clipping_update_period, device=p.device)
316
+ first_state["model_norms"][step % clipping_update_period] = tot_norm
317
+
318
+ if step % clipping_update_period == 0:
319
+ # Print some stats.
320
+ # We don't reach here if step == 0 because we would have returned
321
+ # above.
322
+ sorted_norms = first_state["model_norms"].sort()[0].to("cpu")
323
+ quartiles = []
324
+ for n in range(0, 5):
325
+ index = min(
326
+ clipping_update_period - 1,
327
+ (clipping_update_period // 4) * n,
328
+ )
329
+ quartiles.append(sorted_norms[index].item())
330
+
331
+ median = quartiles[2]
332
+ threshold = clipping_scale * median
333
+ first_state["model_norm_threshold"] = threshold
334
+ percent_clipped = (
335
+ first_state["num_clipped"] * 100.0 / clipping_update_period if "num_clipped" in first_state else 0.0
336
+ )
337
+ first_state["num_clipped"] = 0
338
+ quartiles = " ".join(["%.3e" % x for x in quartiles])
339
+ logging.info(
340
+ f"Clipping_scale={clipping_scale}, grad-norm quartiles {quartiles}, threshold={threshold:.3e}, percent-clipped={percent_clipped:.1f}"
341
+ )
342
+
343
+ if step < clipping_update_period:
344
+ return 1.0 # We have not yet estimated a norm to clip to.
345
+ else:
346
+ try:
347
+ model_norm_threshold = first_state["model_norm_threshold"]
348
+ except KeyError:
349
+ logging.info(
350
+ "Warning: model_norm_threshold not in state: possibly you changed config when restarting, adding clipping_scale option?"
351
+ )
352
+ return 1.0
353
+ ans = min(1.0, (model_norm_threshold / (tot_norm + 1.0e-20)).item())
354
+ if ans < 1.0:
355
+ first_state["num_clipped"] += 1
356
+ if ans < 0.1:
357
+ logging.warn(f"Scaling gradients by {ans}, model_norm_threshold={model_norm_threshold}")
358
+ if self.show_dominant_parameters:
359
+ assert p.shape[0] == len(param_names)
360
+ self._show_gradient_dominating_parameter(tuples, tot_sumsq)
361
+ return ans
362
+
363
+ def _show_gradient_dominating_parameter(self, tuples: List[Tuple[Tensor, dict, List[str]]], tot_sumsq: Tensor):
364
+ """
365
+ Show information of parameter wihch dominanting tot_sumsq.
366
+
367
+ Args:
368
+ tuples: a list of tuples of (param, state, param_names)
369
+ where param is a batched set of parameters,
370
+ with a .grad (1st dim is batch dim)
371
+ and state is the state-dict where optimization parameters are kept.
372
+ param_names is a List[str] while each str is name for a parameter
373
+ in batched set of parameters "param".
374
+ tot_sumsq: sumsq of all parameters. Though it's could be calculated
375
+ from tuples, we still pass it to save some time.
376
+ """
377
+ all_sumsq_orig = {}
378
+ for p, state, batch_param_names in tuples:
379
+ # p is a stacked batch parameters.
380
+ batch_grad = p.grad
381
+ if p.numel() == p.shape[0]: # a batch of scalars
382
+ batch_sumsq_orig = batch_grad**2
383
+ # Dummpy values used by following `zip` statement.
384
+ batch_rms_orig = torch.ones(p.shape[0])
385
+ else:
386
+ batch_rms_orig = state["param_rms"]
387
+ batch_sumsq_orig = ((batch_grad * batch_rms_orig) ** 2).sum(dim=list(range(1, batch_grad.ndim)))
388
+
389
+ for name, sumsq_orig, rms, grad in zip(
390
+ batch_param_names,
391
+ batch_sumsq_orig,
392
+ batch_rms_orig,
393
+ batch_grad,
394
+ ):
395
+ proportion_orig = sumsq_orig / tot_sumsq
396
+ all_sumsq_orig[name] = (proportion_orig, sumsq_orig, rms, grad)
397
+
398
+ assert torch.isclose(
399
+ sum([value[0] for value in all_sumsq_orig.values()]).cpu(),
400
+ torch.tensor(1.0),
401
+ )
402
+ sorted_by_proportion = {
403
+ k: v
404
+ for k, v in sorted(
405
+ all_sumsq_orig.items(),
406
+ key=lambda item: item[1][0],
407
+ reverse=True,
408
+ )
409
+ }
410
+ dominant_param_name = next(iter(sorted_by_proportion))
411
+ (
412
+ dominant_proportion,
413
+ dominant_sumsq,
414
+ dominant_rms,
415
+ dominant_grad,
416
+ ) = sorted_by_proportion[dominant_param_name]
417
+ logging.info(
418
+ f"Parameter Dominanting tot_sumsq {dominant_param_name}"
419
+ f" with proportion {dominant_proportion:.2f},"
420
+ f" where dominant_sumsq=(grad_sumsq*orig_rms_sq)"
421
+ f"={dominant_sumsq:.3e},"
422
+ f" grad_sumsq = {(dominant_grad**2).sum():.3e},"
423
+ f" orig_rms_sq={(dominant_rms**2).item():.3e}"
424
+ )
425
+
426
+ def _step_one_batch(self, group: dict, p: Tensor, state: dict, clipping_scale: float):
427
+ """
428
+ Do the step for one parameter, which is actually going to be a batch of
429
+ `real` parameters, with dim 0 as the batch dim.
430
+ Args:
431
+ group: dict to look up configuration values
432
+ p: parameter to update (actually multiple parameters stacked together
433
+ as a batch)
434
+ state: state-dict for p, to look up the optimizer state
435
+ """
436
+ lr = group["lr"]
437
+ size_update_period = group["size_update_period"]
438
+ beta1 = group["betas"][0]
439
+
440
+ grad = p.grad
441
+ if clipping_scale != 1.0:
442
+ grad = grad * clipping_scale
443
+ step = state["step"]
444
+ delta = state["delta"]
445
+
446
+ delta.mul_(beta1)
447
+ batch_size = p.shape[0]
448
+ numel = p.numel() // batch_size
449
+ if numel > 1:
450
+ # Update the size/scale of p, and set param_rms
451
+ scale_grads = state["scale_grads"]
452
+ scale_grads[step % size_update_period] = (p * grad).sum(dim=list(range(1, p.ndim)), keepdim=True)
453
+ if step % size_update_period == size_update_period - 1:
454
+ param_rms = state["param_rms"] # shape: (batch_size, 1, 1, ..)
455
+ param_rms.copy_((p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt())
456
+ if step > 0:
457
+ # self._size_update() learns the overall scale on the
458
+ # parameter, by shrinking or expanding it.
459
+ self._size_update(group, scale_grads, p, state)
460
+
461
+ if numel == 1:
462
+ # For parameters with 1 element we just use regular Adam.
463
+ # Updates delta.
464
+ self._step_scalar(group, p, state)
465
+ else:
466
+ self._step(group, p, state)
467
+
468
+ state["step"] = step + 1
469
+
470
+ def _size_update(
471
+ self,
472
+ group: dict,
473
+ scale_grads: Tensor,
474
+ p: Tensor,
475
+ state: dict,
476
+ ) -> None:
477
+ """
478
+ Called only where p.numel() > 1, this updates the scale of the parameter.
479
+ If we imagine: p = underlying_param * scale.exp(), and we are doing
480
+ gradient descent on underlying param and on scale, this function does the update
481
+ on `scale`.
482
+
483
+ Args:
484
+ group: dict to look up configuration values
485
+ scale_grads: a tensor of shape (size_update_period, batch_size, 1, 1,...) containing
486
+ grads w.r.t. the scales.
487
+ p: The parameter to update
488
+ state: The state-dict of p
489
+ """
490
+
491
+ param_rms = state["param_rms"]
492
+ beta1, beta2 = group["betas"]
493
+ size_lr = group["lr"] * group["scalar_lr_scale"]
494
+ param_min_rms = group["param_min_rms"]
495
+ param_max_rms = group["param_max_rms"]
496
+ eps = group["eps"]
497
+ step = state["step"]
498
+ batch_size = p.shape[0]
499
+
500
+ size_update_period = scale_grads.shape[0]
501
+ # correct beta2 for the size update period: we will have
502
+ # faster decay at this level.
503
+ beta2_corr = beta2**size_update_period
504
+
505
+ scale_exp_avg_sq = state["scale_exp_avg_sq"] # shape: (batch_size, 1, 1, ..)
506
+ scale_exp_avg_sq.mul_(beta2_corr).add_(
507
+ (scale_grads**2).mean(dim=0), # mean over dim `size_update_period`
508
+ alpha=1 - beta2_corr,
509
+ ) # shape is (batch_size, 1, 1, ...)
510
+
511
+ # The 1st time we reach here is when size_step == 1.
512
+ size_step = (step + 1) // size_update_period
513
+ bias_correction2 = 1 - beta2_corr**size_step
514
+ # we don't bother with bias_correction1; this will help prevent divergence
515
+ # at the start of training.
516
+
517
+ denom = scale_exp_avg_sq.sqrt() + eps
518
+
519
+ scale_step = -size_lr * (bias_correction2**0.5) * scale_grads.sum(dim=0) / denom
520
+
521
+ is_too_small = param_rms < param_min_rms
522
+ is_too_large = param_rms > param_max_rms
523
+
524
+ # when the param gets too small, just don't shrink it any further.
525
+ scale_step.masked_fill_(is_too_small, 0.0)
526
+ # when it gets too large, stop it from getting any larger.
527
+ scale_step.masked_fill_(is_too_large, -size_lr * size_update_period)
528
+ delta = state["delta"]
529
+ # the factor of (1-beta1) relates to momentum.
530
+ delta.add_(p * scale_step, alpha=(1 - beta1))
531
+
532
+ def _step(self, group: dict, p: Tensor, state: dict):
533
+ """
534
+ This function does the core update of self.step(), in the case where the members of
535
+ the batch have more than 1 element.
536
+
537
+ Args:
538
+ group: A dict which will be used to look up configuration values
539
+ p: The parameter to be updated
540
+ grad: The grad of p
541
+ state: The state-dict corresponding to parameter p
542
+
543
+ This function modifies p.
544
+ """
545
+ grad = p.grad
546
+ lr = group["lr"]
547
+ beta1, beta2 = group["betas"]
548
+ eps = group["eps"]
549
+ param_min_rms = group["param_min_rms"]
550
+ step = state["step"]
551
+
552
+ exp_avg_sq = state["exp_avg_sq"]
553
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2))
554
+
555
+ this_step = state["step"] - (state["zero_step"] if "zero_step" in state else 0)
556
+ bias_correction2 = 1 - beta2 ** (this_step + 1)
557
+ if bias_correction2 < 0.99:
558
+ # note: not in-place.
559
+ exp_avg_sq = exp_avg_sq * (1.0 / bias_correction2)
560
+
561
+ denom = exp_avg_sq.sqrt()
562
+ denom += eps
563
+ grad = grad / denom
564
+
565
+ alpha = -lr * (1 - beta1) * state["param_rms"].clamp(min=param_min_rms)
566
+
567
+ delta = state["delta"]
568
+ delta.add_(grad * alpha)
569
+ p.add_(delta)
570
+
571
+ def _step_scalar(self, group: dict, p: Tensor, state: dict):
572
+ """
573
+ A simplified form of the core update for scalar tensors, where we cannot get a good
574
+ estimate of the parameter rms.
575
+ """
576
+ beta1, beta2 = group["betas"]
577
+ scalar_max = group["scalar_max"]
578
+ eps = group["eps"]
579
+ lr = group["lr"] * group["scalar_lr_scale"]
580
+ grad = p.grad
581
+
582
+ exp_avg_sq = state["exp_avg_sq"] # shape: (batch_size,)
583
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
584
+
585
+ # bias_correction2 is like in Adam. Don't bother with bias_correction1;
586
+ # slower update at the start will help stability anyway.
587
+ bias_correction2 = 1 - beta2 ** (state["step"] + 1)
588
+ denom = (exp_avg_sq / bias_correction2).sqrt() + eps
589
+
590
+ delta = state["delta"]
591
+ delta.add_(grad / denom, alpha=-lr * (1 - beta1))
592
+ p.clamp_(min=-scalar_max, max=scalar_max)
593
+ p.add_(delta)
GPT_SoVITS/AR/modules/patched_mha_with_cache.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn.functional import *
2
+ from torch.nn.functional import (
3
+ _mha_shape_check,
4
+ _canonical_mask,
5
+ _none_or_dtype,
6
+ _in_projection_packed,
7
+ )
8
+ import torch
9
+ # Tensor = torch.Tensor
10
+ # from typing import Callable, List, Optional, Tuple, Union
11
+
12
+
13
+ def multi_head_attention_forward_patched(
14
+ query,
15
+ key,
16
+ value,
17
+ embed_dim_to_check,
18
+ num_heads,
19
+ in_proj_weight,
20
+ in_proj_bias,
21
+ bias_k,
22
+ bias_v,
23
+ add_zero_attn,
24
+ dropout_p: float,
25
+ out_proj_weight,
26
+ out_proj_bias,
27
+ training=True,
28
+ key_padding_mask=None,
29
+ need_weights=True,
30
+ attn_mask=None,
31
+ use_separate_proj_weight=False,
32
+ q_proj_weight=None,
33
+ k_proj_weight=None,
34
+ v_proj_weight=None,
35
+ static_k=None,
36
+ static_v=None,
37
+ average_attn_weights=True,
38
+ is_causal=False,
39
+ cache=None,
40
+ ):
41
+ r"""
42
+ Args:
43
+ query, key, value: map a query and a set of key-value pairs to an output.
44
+ See "Attention Is All You Need" for more details.
45
+ embed_dim_to_check: total dimension of the model.
46
+ num_heads: parallel attention heads.
47
+ in_proj_weight, in_proj_bias: input projection weight and bias.
48
+ bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
49
+ add_zero_attn: add a new batch of zeros to the key and
50
+ value sequences at dim=1.
51
+ dropout_p: probability of an element to be zeroed.
52
+ out_proj_weight, out_proj_bias: the output projection weight and bias.
53
+ training: apply dropout if is ``True``.
54
+ key_padding_mask: if provided, specified padding elements in the key will
55
+ be ignored by the attention. This is an binary mask. When the value is True,
56
+ the corresponding value on the attention layer will be filled with -inf.
57
+ need_weights: output attn_output_weights.
58
+ Default: `True`
59
+ Note: `needs_weight` defaults to `True`, but should be set to `False`
60
+ For best performance when attention weights are not nedeeded.
61
+ *Setting needs_weights to `True`
62
+ leads to a significant performance degradation.*
63
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
64
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
65
+ is_causal: If specified, applies a causal mask as attention mask, and ignores
66
+ attn_mask for computing scaled dot product attention.
67
+ Default: ``False``.
68
+ .. warning::
69
+ is_causal is provides a hint that the attn_mask is the
70
+ causal mask.Providing incorrect hints can result in
71
+ incorrect execution, including forward and backward
72
+ compatibility.
73
+ use_separate_proj_weight: the function accept the proj. weights for query, key,
74
+ and value in different forms. If false, in_proj_weight will be used, which is
75
+ a combination of q_proj_weight, k_proj_weight, v_proj_weight.
76
+ q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
77
+ static_k, static_v: static key and value used for attention operators.
78
+ average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
79
+ Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
80
+ when ``need_weights=True.``. Default: True
81
+
82
+
83
+ Shape:
84
+ Inputs:
85
+ - query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
86
+ the embedding dimension.
87
+ - key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
88
+ the embedding dimension.
89
+ - value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
90
+ the embedding dimension.
91
+ - key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
92
+ If a FloatTensor is provided, it will be directly added to the value.
93
+ If a BoolTensor is provided, the positions with the
94
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
95
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
96
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
97
+ S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
98
+ positions. If a BoolTensor is provided, positions with ``True``
99
+ are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
100
+ is provided, it will be added to the attention weight.
101
+ - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
102
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
103
+ - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
104
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
105
+
106
+ Outputs:
107
+ - attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
108
+ E is the embedding dimension.
109
+ - attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
110
+ attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
111
+ :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
112
+ :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
113
+ head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
114
+ """
115
+ tens_ops = (
116
+ query,
117
+ key,
118
+ value,
119
+ in_proj_weight,
120
+ in_proj_bias,
121
+ bias_k,
122
+ bias_v,
123
+ out_proj_weight,
124
+ out_proj_bias,
125
+ )
126
+ if has_torch_function(tens_ops):
127
+ return handle_torch_function(
128
+ multi_head_attention_forward,
129
+ tens_ops,
130
+ query,
131
+ key,
132
+ value,
133
+ embed_dim_to_check,
134
+ num_heads,
135
+ in_proj_weight,
136
+ in_proj_bias,
137
+ bias_k,
138
+ bias_v,
139
+ add_zero_attn,
140
+ dropout_p,
141
+ out_proj_weight,
142
+ out_proj_bias,
143
+ training=training,
144
+ key_padding_mask=key_padding_mask,
145
+ need_weights=need_weights,
146
+ attn_mask=attn_mask,
147
+ is_causal=is_causal,
148
+ use_separate_proj_weight=use_separate_proj_weight,
149
+ q_proj_weight=q_proj_weight,
150
+ k_proj_weight=k_proj_weight,
151
+ v_proj_weight=v_proj_weight,
152
+ static_k=static_k,
153
+ static_v=static_v,
154
+ average_attn_weights=average_attn_weights,
155
+ cache=cache,
156
+ )
157
+
158
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
159
+
160
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
161
+ # is batched, run the computation and before returning squeeze the
162
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
163
+ if not is_batched:
164
+ # unsqueeze if the input is unbatched
165
+ query = query.unsqueeze(1)
166
+ key = key.unsqueeze(1)
167
+ value = value.unsqueeze(1)
168
+ if key_padding_mask is not None:
169
+ key_padding_mask = key_padding_mask.unsqueeze(0)
170
+
171
+ # set up shape vars
172
+ tgt_len, bsz, embed_dim = query.shape
173
+ src_len, _, _ = key.shape
174
+
175
+ key_padding_mask = _canonical_mask(
176
+ mask=key_padding_mask,
177
+ mask_name="key_padding_mask",
178
+ other_type=_none_or_dtype(attn_mask),
179
+ other_name="attn_mask",
180
+ target_type=query.dtype,
181
+ )
182
+
183
+ if is_causal and attn_mask is None:
184
+ raise RuntimeError(
185
+ "Need attn_mask if specifying the is_causal hint. "
186
+ "You may use the Transformer module method "
187
+ "`generate_square_subsequent_mask` to create this mask."
188
+ )
189
+
190
+ if is_causal and key_padding_mask is None and not need_weights:
191
+ # when we have a kpm or need weights, we need attn_mask
192
+ # Otherwise, we use the is_causal hint go as is_causal
193
+ # indicator to SDPA.
194
+ attn_mask = None
195
+ else:
196
+ attn_mask = _canonical_mask(
197
+ mask=attn_mask,
198
+ mask_name="attn_mask",
199
+ other_type=None,
200
+ other_name="",
201
+ target_type=query.dtype,
202
+ check_other=False,
203
+ )
204
+
205
+ if key_padding_mask is not None:
206
+ # We have the attn_mask, and use that to merge kpm into it.
207
+ # Turn off use of is_causal hint, as the merged mask is no
208
+ # longer causal.
209
+ is_causal = False
210
+
211
+ assert embed_dim == embed_dim_to_check, (
212
+ f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
213
+ )
214
+ if isinstance(embed_dim, torch.Tensor):
215
+ # embed_dim can be a tensor when JIT tracing
216
+ head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
217
+ else:
218
+ head_dim = embed_dim // num_heads
219
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
220
+ if use_separate_proj_weight:
221
+ # allow MHA to have different embedding dimensions when separate projection weights are used
222
+ assert key.shape[:2] == value.shape[:2], (
223
+ f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
224
+ )
225
+ else:
226
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
227
+
228
+ #
229
+ # compute in-projection
230
+ #
231
+ if not use_separate_proj_weight:
232
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
233
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
234
+ else:
235
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
236
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
237
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
238
+ if in_proj_bias is None:
239
+ b_q = b_k = b_v = None
240
+ else:
241
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
242
+ q, k, v = _in_projection(
243
+ query,
244
+ key,
245
+ value,
246
+ q_proj_weight,
247
+ k_proj_weight,
248
+ v_proj_weight,
249
+ b_q,
250
+ b_k,
251
+ b_v,
252
+ )
253
+ if cache != None:
254
+ if cache["first_infer"] == 1:
255
+ cache["k"][cache["stage"]] = k
256
+ # print(0,cache["k"].shape)
257
+ cache["v"][cache["stage"]] = v
258
+ else: ###12个layer每个都要留自己的cache_kv
259
+ # print(1,cache["k"].shape)
260
+ cache["k"][cache["stage"]] = torch.cat(
261
+ [cache["k"][cache["stage"]], k], 0
262
+ ) ##本来时序是1,但是proj的时候可能transpose了所以时序到0维了
263
+ cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]], v], 0)
264
+ # print(2, cache["k"].shape)
265
+ src_len = cache["k"][cache["stage"]].shape[0]
266
+ k = cache["k"][cache["stage"]]
267
+ v = cache["v"][cache["stage"]]
268
+ # if attn_mask is not None:
269
+ # attn_mask=attn_mask[-1:,]
270
+ # print(attn_mask.shape,attn_mask)
271
+ cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
272
+ # print(2333,cache)
273
+ # prep attention mask
274
+
275
+ attn_mask = _canonical_mask(
276
+ mask=attn_mask,
277
+ mask_name="attn_mask",
278
+ other_type=None,
279
+ other_name="",
280
+ target_type=q.dtype,
281
+ check_other=False,
282
+ )
283
+
284
+ if attn_mask is not None:
285
+ # ensure attn_mask's dim is 3
286
+ if attn_mask.dim() == 2:
287
+ correct_2d_size = (tgt_len, src_len)
288
+ if attn_mask.shape != correct_2d_size:
289
+ raise RuntimeError(
290
+ f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
291
+ )
292
+ attn_mask = attn_mask.unsqueeze(0)
293
+ elif attn_mask.dim() == 3:
294
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
295
+ if attn_mask.shape != correct_3d_size:
296
+ raise RuntimeError(
297
+ f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
298
+ )
299
+ else:
300
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
301
+
302
+ # add bias along batch dimension (currently second)
303
+ if bias_k is not None and bias_v is not None:
304
+ assert static_k is None, "bias cannot be added to static key."
305
+ assert static_v is None, "bias cannot be added to static value."
306
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
307
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
308
+ if attn_mask is not None:
309
+ attn_mask = pad(attn_mask, (0, 1))
310
+ if key_padding_mask is not None:
311
+ key_padding_mask = pad(key_padding_mask, (0, 1))
312
+ else:
313
+ assert bias_k is None
314
+ assert bias_v is None
315
+
316
+ #
317
+ # reshape q, k, v for multihead attention and make em batch first
318
+ #
319
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
320
+ if static_k is None:
321
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
322
+ else:
323
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
324
+ assert static_k.size(0) == bsz * num_heads, (
325
+ f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
326
+ )
327
+ assert static_k.size(2) == head_dim, f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
328
+ k = static_k
329
+ if static_v is None:
330
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
331
+ else:
332
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
333
+ assert static_v.size(0) == bsz * num_heads, (
334
+ f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
335
+ )
336
+ assert static_v.size(2) == head_dim, f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
337
+ v = static_v
338
+
339
+ # add zero attention along batch dimension (now first)
340
+ if add_zero_attn:
341
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
342
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
343
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
344
+ if attn_mask is not None:
345
+ attn_mask = pad(attn_mask, (0, 1))
346
+ if key_padding_mask is not None:
347
+ key_padding_mask = pad(key_padding_mask, (0, 1))
348
+
349
+ # update source sequence length after adjustments
350
+ src_len = k.size(1)
351
+
352
+ # merge key padding and attention masks
353
+ if key_padding_mask is not None:
354
+ assert key_padding_mask.shape == (
355
+ bsz,
356
+ src_len,
357
+ ), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
358
+ key_padding_mask = (
359
+ key_padding_mask.view(bsz, 1, 1, src_len).expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
360
+ )
361
+ if attn_mask is None:
362
+ attn_mask = key_padding_mask
363
+ else:
364
+ attn_mask = attn_mask + key_padding_mask
365
+
366
+ # adjust dropout probability
367
+ if not training:
368
+ dropout_p = 0.0
369
+
370
+ #
371
+ # (deep breath) calculate attention and out projection
372
+ #
373
+
374
+ if need_weights:
375
+ B, Nt, E = q.shape
376
+ q_scaled = q / math.sqrt(E)
377
+
378
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
379
+
380
+ if attn_mask is not None:
381
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
382
+ else:
383
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
384
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
385
+ if dropout_p > 0.0:
386
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
387
+
388
+ attn_output = torch.bmm(attn_output_weights, v)
389
+
390
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
391
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
392
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
393
+
394
+ # optionally average attention weights over heads
395
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
396
+ if average_attn_weights:
397
+ attn_output_weights = attn_output_weights.mean(dim=1)
398
+
399
+ if not is_batched:
400
+ # squeeze the output if input was unbatched
401
+ attn_output = attn_output.squeeze(1)
402
+ attn_output_weights = attn_output_weights.squeeze(0)
403
+ return attn_output, attn_output_weights
404
+ else:
405
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
406
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
407
+ # in order to match the input for SDPA of (N, num_heads, L, S)
408
+ if attn_mask is not None:
409
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
410
+ attn_mask = attn_mask.unsqueeze(0)
411
+ else:
412
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
413
+
414
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
415
+ k = k.view(bsz, num_heads, src_len, head_dim)
416
+ v = v.view(bsz, num_heads, src_len, head_dim)
417
+
418
+ # with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
419
+ attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
420
+
421
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
422
+
423
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
424
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
425
+ if not is_batched:
426
+ # squeeze the output if input was unbatched
427
+ attn_output = attn_output.squeeze(1)
428
+ return attn_output, None
GPT_SoVITS/AR/modules/patched_mha_with_cache_onnx.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn.functional import *
2
+ from torch.nn.functional import (
3
+ _canonical_mask,
4
+ )
5
+
6
+
7
+ def multi_head_attention_forward_patched(
8
+ query,
9
+ key,
10
+ value,
11
+ embed_dim_to_check: int,
12
+ num_heads: int,
13
+ in_proj_weight,
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,
33
+ cache=None,
34
+ ) -> Tuple[Tensor, Optional[Tensor]]:
35
+ # set up shape vars
36
+ _, _, embed_dim = query.shape
37
+ attn_mask = _canonical_mask(
38
+ mask=attn_mask,
39
+ mask_name="attn_mask",
40
+ other_type=None,
41
+ other_name="",
42
+ target_type=query.dtype,
43
+ check_other=False,
44
+ )
45
+ head_dim = embed_dim // num_heads
46
+
47
+ proj_qkv = linear(query, in_proj_weight, in_proj_bias)
48
+ proj_qkv = proj_qkv.unflatten(-1, (3, query.size(-1))).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
49
+ q, k, v = proj_qkv[0], proj_qkv[1], proj_qkv[2]
50
+
51
+ if cache["first_infer"] == 1:
52
+ cache["k"][cache["stage"]] = k
53
+ cache["v"][cache["stage"]] = v
54
+ else:
55
+ cache["k"][cache["stage"]] = torch.cat([cache["k"][cache["stage"]][:-1], k], 0)
56
+ cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]][:-1], v], 0)
57
+ k = cache["k"][cache["stage"]]
58
+ v = cache["v"][cache["stage"]]
59
+ cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
60
+
61
+ attn_mask = _canonical_mask(
62
+ mask=attn_mask,
63
+ mask_name="attn_mask",
64
+ other_type=None,
65
+ other_name="",
66
+ target_type=q.dtype,
67
+ check_other=False,
68
+ )
69
+ attn_mask = attn_mask.unsqueeze(0)
70
+
71
+ q = q.view(-1, num_heads, head_dim).transpose(0, 1)
72
+ k = k.view(-1, num_heads, head_dim).transpose(0, 1)
73
+ v = v.view(-1, num_heads, head_dim).transpose(0, 1)
74
+
75
+ dropout_p = 0.0
76
+ attn_mask = attn_mask.unsqueeze(0)
77
+ q = q.view(num_heads, -1, head_dim).unsqueeze(0)
78
+ k = k.view(num_heads, -1, head_dim).unsqueeze(0)
79
+ v = v.view(num_heads, -1, head_dim).unsqueeze(0)
80
+ attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
81
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(-1, embed_dim)
82
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
83
+ attn_output = attn_output.view(-1, 1, attn_output.size(1))
84
+
85
+ return attn_output
GPT_SoVITS/AR/modules/scaling.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 random
17
+ from typing import Optional
18
+ from typing import Tuple
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ from torch import Tensor
23
+
24
+
25
+ class DoubleSwishFunction(torch.autograd.Function):
26
+ """
27
+ double_swish(x) = x * torch.sigmoid(x-1)
28
+ This is a definition, originally motivated by its close numerical
29
+ similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
30
+
31
+ Memory-efficient derivative computation:
32
+ double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
33
+ double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
34
+ Now, s'(x) = s(x) * (1-s(x)).
35
+ double_swish'(x) = x * s'(x) + s(x).
36
+ = x * s(x) * (1-s(x)) + s(x).
37
+ = double_swish(x) * (1-s(x)) + s(x)
38
+ ... so we just need to remember s(x) but not x itself.
39
+ """
40
+
41
+ @staticmethod
42
+ def forward(ctx, x: Tensor) -> Tensor:
43
+ requires_grad = x.requires_grad
44
+ x_dtype = x.dtype
45
+ if x.dtype == torch.float16:
46
+ x = x.to(torch.float32)
47
+
48
+ s = torch.sigmoid(x - 1.0)
49
+ y = x * s
50
+
51
+ if requires_grad:
52
+ deriv = y * (1 - s) + s
53
+ # notes on derivative of x * sigmoid(x - 1):
54
+ # https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
55
+ # min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
56
+ # max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
57
+ # the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
58
+ # floors), should be expectation-preserving.
59
+ floor = -0.043637
60
+ ceil = 1.2
61
+ d_scaled = (deriv - floor) * (255.0 / (ceil - floor)) + torch.rand_like(deriv)
62
+ if __name__ == "__main__":
63
+ # for self-testing only.
64
+ assert d_scaled.min() >= 0.0
65
+ assert d_scaled.max() < 256.0
66
+ d_int = d_scaled.to(torch.uint8)
67
+ ctx.save_for_backward(d_int)
68
+ if x.dtype == torch.float16 or torch.is_autocast_enabled():
69
+ y = y.to(torch.float16)
70
+ return y
71
+
72
+ @staticmethod
73
+ def backward(ctx, y_grad: Tensor) -> Tensor:
74
+ (d,) = ctx.saved_tensors
75
+ # the same constants as used in forward pass.
76
+ floor = -0.043637
77
+ ceil = 1.2
78
+ d = d * ((ceil - floor) / 255.0) + floor
79
+ return y_grad * d
80
+
81
+
82
+ class DoubleSwish(torch.nn.Module):
83
+ def forward(self, x: Tensor) -> Tensor:
84
+ """Return double-swish activation function which is an approximation to Swish(Swish(x)),
85
+ that we approximate closely with x * sigmoid(x-1).
86
+ """
87
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
88
+ return x * torch.sigmoid(x - 1.0)
89
+ return DoubleSwishFunction.apply(x)
90
+
91
+
92
+ class ActivationBalancerFunction(torch.autograd.Function):
93
+ @staticmethod
94
+ def forward(
95
+ ctx,
96
+ x: Tensor,
97
+ scale_factor: Tensor,
98
+ sign_factor: Optional[Tensor],
99
+ channel_dim: int,
100
+ ) -> Tensor:
101
+ if channel_dim < 0:
102
+ channel_dim += x.ndim
103
+ ctx.channel_dim = channel_dim
104
+ xgt0 = x > 0
105
+ if sign_factor is None:
106
+ ctx.save_for_backward(xgt0, scale_factor)
107
+ else:
108
+ ctx.save_for_backward(xgt0, scale_factor, sign_factor)
109
+ return x
110
+
111
+ @staticmethod
112
+ def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
113
+ if len(ctx.saved_tensors) == 3:
114
+ xgt0, scale_factor, sign_factor = ctx.saved_tensors
115
+ for _ in range(ctx.channel_dim, x_grad.ndim - 1):
116
+ scale_factor = scale_factor.unsqueeze(-1)
117
+ sign_factor = sign_factor.unsqueeze(-1)
118
+ factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
119
+ else:
120
+ xgt0, scale_factor = ctx.saved_tensors
121
+ for _ in range(ctx.channel_dim, x_grad.ndim - 1):
122
+ scale_factor = scale_factor.unsqueeze(-1)
123
+ factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
124
+ neg_delta_grad = x_grad.abs() * factor
125
+ return (
126
+ x_grad - neg_delta_grad,
127
+ None,
128
+ None,
129
+ None,
130
+ )
131
+
132
+
133
+ def _compute_scale_factor(
134
+ x: Tensor,
135
+ channel_dim: int,
136
+ min_abs: float,
137
+ max_abs: float,
138
+ gain_factor: float,
139
+ max_factor: float,
140
+ ) -> Tensor:
141
+ if channel_dim < 0:
142
+ channel_dim += x.ndim
143
+ sum_dims = [d for d in range(x.ndim) if d != channel_dim]
144
+ x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
145
+
146
+ if min_abs == 0.0:
147
+ below_threshold = 0.0
148
+ else:
149
+ # below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
150
+ # x_abs)_mean , min_abs.
151
+ below_threshold = ((min_abs - x_abs_mean) * (gain_factor / min_abs)).clamp(min=0, max=max_factor)
152
+
153
+ above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(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,
165
+ ) -> Tensor:
166
+ if channel_dim < 0:
167
+ channel_dim += x.ndim
168
+ sum_dims = [d for d in range(x.ndim) if d != channel_dim]
169
+ proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
170
+ if min_positive == 0.0:
171
+ factor1 = 0.0
172
+ else:
173
+ # 0 if proportion_positive >= min_positive, else can be
174
+ # as large as max_factor.
175
+ factor1 = ((min_positive - proportion_positive) * (gain_factor / min_positive)).clamp_(min=0, max=max_factor)
176
+
177
+ if max_positive == 1.0:
178
+ factor2 = 0.0
179
+ else:
180
+ # 0 if self.proportion_positive <= max_positive, else can be
181
+ # as large as -max_factor.
182
+ factor2 = ((proportion_positive - max_positive) * (gain_factor / (1.0 - max_positive))).clamp_(
183
+ min=0, max=max_factor
184
+ )
185
+ sign_factor = factor1 - factor2
186
+ # require min_positive != 0 or max_positive != 1:
187
+ assert not isinstance(sign_factor, float)
188
+ return sign_factor
189
+
190
+
191
+ class ActivationBalancer(torch.nn.Module):
192
+ """
193
+ Modifies the backpropped derivatives of a function to try to encourage, for
194
+ each channel, that it is positive at least a proportion `threshold` of the
195
+ time. It does this by multiplying negative derivative values by up to
196
+ (1+max_factor), and positive derivative values by up to (1-max_factor),
197
+ interpolated from 1 at the threshold to those extremal values when none
198
+ of the inputs are positive.
199
+
200
+ Args:
201
+ num_channels: the number of channels
202
+ channel_dim: the dimension/axis corresponding to the channel, e.g.
203
+ -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
204
+ min_positive: the minimum, per channel, of the proportion of the time
205
+ that (x > 0), below which we start to modify the derivatives.
206
+ max_positive: the maximum, per channel, of the proportion of the time
207
+ that (x > 0), above which we start to modify the derivatives.
208
+ max_factor: the maximum factor by which we modify the derivatives for
209
+ either the sign constraint or the magnitude constraint;
210
+ e.g. with max_factor=0.02, the the derivatives would be multiplied by
211
+ values in the range [0.98..1.02].
212
+ sign_gain_factor: determines the 'gain' with which we increase the
213
+ change in gradient once the constraints on min_positive and max_positive
214
+ are violated.
215
+ scale_gain_factor: determines the 'gain' with which we increase the
216
+ change in gradient once the constraints on min_abs and max_abs
217
+ are violated.
218
+ min_abs: the minimum average-absolute-value difference from the mean
219
+ value per channel, which we allow, before we start to modify
220
+ the derivatives to prevent this.
221
+ max_abs: the maximum average-absolute-value difference from the mean
222
+ value per channel, which we allow, before we start to modify
223
+ the derivatives to prevent this.
224
+ min_prob: determines the minimum probability with which we modify the
225
+ gradients for the {min,max}_positive and {min,max}_abs constraints,
226
+ on each forward(). This is done randomly to prevent all layers
227
+ from doing it at the same time. Early in training we may use
228
+ higher probabilities than this; it will decay to this value.
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ num_channels: int,
234
+ channel_dim: int,
235
+ min_positive: float = 0.05,
236
+ max_positive: float = 0.95,
237
+ max_factor: float = 0.04,
238
+ sign_gain_factor: float = 0.01,
239
+ scale_gain_factor: float = 0.02,
240
+ min_abs: float = 0.2,
241
+ max_abs: float = 100.0,
242
+ min_prob: float = 0.1,
243
+ ):
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 torch.jit.is_tracing():
264
+ return _no_op(x)
265
+
266
+ count = self.cpu_count
267
+ self.cpu_count += 1
268
+
269
+ if random.random() < 0.01:
270
+ # Occasionally sync self.cpu_count with self.count.
271
+ # count affects the decay of 'prob'. don't do this on every iter,
272
+ # because syncing with the GPU is slow.
273
+ self.cpu_count = max(self.cpu_count, self.count.item())
274
+ self.count.fill_(self.cpu_count)
275
+
276
+ # the prob of doing some work exponentially decreases from 0.5 till it hits
277
+ # a floor at min_prob (==0.1, by default)
278
+ prob = max(self.min_prob, 0.5 ** (1 + (count / 4000.0)))
279
+
280
+ if random.random() < prob:
281
+ sign_gain_factor = 0.5
282
+ if self.min_positive != 0.0 or self.max_positive != 1.0:
283
+ sign_factor = _compute_sign_factor(
284
+ x,
285
+ self.channel_dim,
286
+ self.min_positive,
287
+ self.max_positive,
288
+ gain_factor=self.sign_gain_factor / prob,
289
+ max_factor=self.max_factor,
290
+ )
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
+ )
302
+ return ActivationBalancerFunction.apply(
303
+ x,
304
+ scale_factor,
305
+ sign_factor,
306
+ self.channel_dim,
307
+ )
308
+ else:
309
+ return _no_op(x)
310
+
311
+
312
+ def BalancedDoubleSwish(d_model, channel_dim=-1, max_abs=10.0, min_prob=0.25) -> nn.Sequential:
313
+ """
314
+ ActivationBalancer -> DoubleSwish
315
+ """
316
+ balancer = ActivationBalancer(d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob)
317
+ return nn.Sequential(
318
+ balancer,
319
+ DoubleSwish(),
320
+ )
GPT_SoVITS/AR/modules/transformer.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
35
+ ) -> None:
36
+ factory_kwargs = {"device": device, "dtype": dtype}
37
+ super(LayerNorm, self).__init__()
38
+ if isinstance(normalized_shape, numbers.Integral):
39
+ # mypy error: incompatible types in assignment
40
+ normalized_shape = (normalized_shape,) # type: ignore[assignment]
41
+ self.normalized_shape = tuple(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(torch.empty(self.normalized_shape, **factory_kwargs))
46
+ self.bias = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
47
+ else:
48
+ self.register_parameter("weight", None)
49
+ self.register_parameter("bias", None)
50
+
51
+ self.reset_parameters()
52
+
53
+ def reset_parameters(self) -> None:
54
+ if self.elementwise_affine:
55
+ nn.init.ones_(self.weight)
56
+ nn.init.zeros_(self.bias)
57
+
58
+ def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
59
+ if isinstance(input, tuple):
60
+ input, embedding = input
61
+ return (
62
+ F.layer_norm(
63
+ input,
64
+ self.normalized_shape,
65
+ self.weight,
66
+ self.bias,
67
+ self.eps,
68
+ ),
69
+ embedding,
70
+ )
71
+
72
+ assert embedding is None
73
+ return F.layer_norm(input, self.normalized_shape, self.weight, self.bias, self.eps)
74
+
75
+ def extra_repr(self) -> str:
76
+ return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
77
+
78
+
79
+ class IdentityNorm(nn.Module):
80
+ def __init__(
81
+ self,
82
+ d_model: int,
83
+ eps: float = 1e-5,
84
+ device=None,
85
+ dtype=None,
86
+ ) -> 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
+
116
+ __constants__ = ["norm"]
117
+
118
+ def __init__(self, encoder_layer, num_layers, norm=None):
119
+ super(TransformerEncoder, self).__init__()
120
+ self.layers = _get_clones(encoder_layer, num_layers)
121
+ self.num_layers = num_layers
122
+ self.norm = norm
123
+
124
+ def forward(
125
+ self,
126
+ src: Tensor,
127
+ mask: Optional[Tensor] = None,
128
+ src_key_padding_mask: Optional[Tensor] = None,
129
+ return_layer_states: bool = False,
130
+ cache=None,
131
+ ) -> Tensor:
132
+ r"""Pass the input through the encoder layers in turn.
133
+
134
+ Args:
135
+ src: the sequence to the encoder (required).
136
+ mask: the mask for the src sequence (optional).
137
+ src_key_padding_mask: the mask for the src keys per batch (optional).
138
+ return_layer_states: return layers' state (optional).
139
+
140
+ Shape:
141
+ see the docs in Transformer class.
142
+ """
143
+ if return_layer_states:
144
+ layer_states = [] # layers' output
145
+ output = src
146
+ for mod in self.layers:
147
+ output = mod(
148
+ output,
149
+ src_mask=mask,
150
+ src_key_padding_mask=src_key_padding_mask,
151
+ cache=cache,
152
+ )
153
+ layer_states.append(output[0])
154
+
155
+ if self.norm is not None:
156
+ output = self.norm(output)
157
+
158
+ return layer_states, output
159
+
160
+ output = src
161
+ for mod in self.layers:
162
+ output = mod(
163
+ output,
164
+ src_mask=mask,
165
+ src_key_padding_mask=src_key_padding_mask,
166
+ cache=cache,
167
+ )
168
+
169
+ if self.norm is not None:
170
+ output = self.norm(output)
171
+
172
+ return output
173
+
174
+
175
+ class TransformerEncoderLayer(nn.Module):
176
+ __constants__ = ["batch_first", "norm_first"]
177
+
178
+ def __init__(
179
+ self,
180
+ d_model: int,
181
+ nhead: int,
182
+ dim_feedforward: int = 2048,
183
+ dropout: float = 0.1,
184
+ activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
185
+ batch_first: bool = False,
186
+ norm_first: bool = False,
187
+ device=None,
188
+ dtype=None,
189
+ linear1_self_attention_cls: nn.Module = nn.Linear,
190
+ linear2_self_attention_cls: nn.Module = nn.Linear,
191
+ linear1_feedforward_cls: nn.Module = nn.Linear,
192
+ linear2_feedforward_cls: nn.Module = nn.Linear,
193
+ layer_norm_cls: nn.Module = LayerNorm,
194
+ layer_norm_eps: float = 1e-5,
195
+ adaptive_layer_norm=False,
196
+ ) -> None:
197
+ factory_kwargs = {"device": device, "dtype": dtype}
198
+ super(TransformerEncoderLayer, self).__init__()
199
+ # print(233333333333,d_model,nhead)
200
+ # import os
201
+ # os._exit(2333333)
202
+ self.self_attn = MultiheadAttention(
203
+ d_model, # 512 16
204
+ nhead,
205
+ dropout=dropout,
206
+ batch_first=batch_first,
207
+ linear1_cls=linear1_self_attention_cls,
208
+ linear2_cls=linear2_self_attention_cls,
209
+ **factory_kwargs,
210
+ )
211
+
212
+ # Implementation of Feedforward model
213
+ self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
214
+ self.dropout = nn.Dropout(dropout)
215
+ self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
216
+
217
+ self.norm_first = norm_first
218
+ self.dropout1 = nn.Dropout(dropout)
219
+ self.dropout2 = nn.Dropout(dropout)
220
+
221
+ # Legacy string support for activation function.
222
+ if isinstance(activation, str):
223
+ activation = _get_activation_fn(activation)
224
+ elif isinstance(activation, partial):
225
+ activation = activation(d_model)
226
+ elif activation == BalancedDoubleSwish:
227
+ activation = BalancedDoubleSwish(d_model)
228
+
229
+ # # We can't test self.activation in forward() in TorchScript,
230
+ # # so stash some information about it instead.
231
+ # if activation is F.relu or isinstance(activation, torch.nn.ReLU):
232
+ # self.activation_relu_or_gelu = 1
233
+ # elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
234
+ # self.activation_relu_or_gelu = 2
235
+ # else:
236
+ # self.activation_relu_or_gelu = 0
237
+ self.activation = activation
238
+
239
+ norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
240
+ if layer_norm_cls == IdentityNorm:
241
+ norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
242
+ else:
243
+ norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
244
+
245
+ if adaptive_layer_norm:
246
+ self.norm1 = AdaptiveLayerNorm(d_model, norm1)
247
+ self.norm2 = AdaptiveLayerNorm(d_model, norm2)
248
+ else:
249
+ self.norm1 = norm1
250
+ self.norm2 = norm2
251
+
252
+ def __setstate__(self, state):
253
+ super(TransformerEncoderLayer, self).__setstate__(state)
254
+ if not hasattr(self, "activation"):
255
+ self.activation = F.relu
256
+
257
+ def forward(
258
+ self,
259
+ src: Tensor,
260
+ src_mask: Optional[Tensor] = None,
261
+ src_key_padding_mask: Optional[Tensor] = None,
262
+ cache=None,
263
+ ) -> Tensor:
264
+ r"""Pass the input through the encoder layer.
265
+
266
+ Args:
267
+ src: the sequence to the encoder layer (required).
268
+ src_mask: the mask for the src sequence (optional).
269
+ src_key_padding_mask: the mask for the src keys per batch (optional).
270
+
271
+ Shape:
272
+ see the docs in Transformer class.
273
+ """
274
+ x, stage_embedding = src, None
275
+ is_src_tuple = False
276
+ if isinstance(src, tuple):
277
+ x, stage_embedding = src
278
+ is_src_tuple = True
279
+
280
+ if src_key_padding_mask is not None:
281
+ _skpm_dtype = src_key_padding_mask.dtype
282
+ if _skpm_dtype != torch.bool and not torch.is_floating_point(src_key_padding_mask):
283
+ raise AssertionError("only bool and floating types of key_padding_mask are supported")
284
+
285
+ if self.norm_first:
286
+ x = x + self._sa_block(
287
+ self.norm1(x, stage_embedding),
288
+ src_mask,
289
+ src_key_padding_mask,
290
+ cache=cache,
291
+ )
292
+ x = x + self._ff_block(self.norm2(x, stage_embedding))
293
+ else:
294
+ x = self.norm1(
295
+ x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
296
+ stage_embedding,
297
+ )
298
+ x = self.norm2(x + self._ff_block(x), stage_embedding)
299
+
300
+ if is_src_tuple:
301
+ return (x, stage_embedding)
302
+ return x
303
+
304
+ # self-attention block
305
+ def _sa_block(
306
+ self,
307
+ x: Tensor,
308
+ attn_mask: Optional[Tensor],
309
+ key_padding_mask: Optional[Tensor],
310
+ cache=None,
311
+ ) -> Tensor:
312
+ # print(x.shape,attn_mask.shape,key_padding_mask)
313
+ # torch.Size([1, 188, 512]) torch.Size([188, 188]) None
314
+ # import os
315
+ # os._exit(23333)
316
+ x = self.self_attn(
317
+ x,
318
+ x,
319
+ x,
320
+ attn_mask=attn_mask,
321
+ key_padding_mask=key_padding_mask,
322
+ need_weights=False,
323
+ cache=cache,
324
+ )[0]
325
+ return self.dropout1(x)
326
+
327
+ # feed forward block
328
+ def _ff_block(self, x: Tensor) -> Tensor:
329
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
330
+ return self.dropout2(x)
331
+
332
+
333
+ class AdaptiveLayerNorm(nn.Module):
334
+ r"""Adaptive Layer Normalization"""
335
+
336
+ def __init__(self, d_model, norm) -> None:
337
+ super(AdaptiveLayerNorm, self).__init__()
338
+ self.project_layer = nn.Linear(d_model, 2 * d_model)
339
+ self.norm = norm
340
+ self.d_model = d_model
341
+ self.eps = self.norm.eps
342
+
343
+ def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
344
+ if isinstance(input, tuple):
345
+ input, embedding = input
346
+ weight, bias = torch.split(
347
+ self.project_layer(embedding),
348
+ split_size_or_sections=self.d_model,
349
+ dim=-1,
350
+ )
351
+ return (weight * self.norm(input) + bias, embedding)
352
+
353
+ weight, bias = torch.split(
354
+ self.project_layer(embedding),
355
+ split_size_or_sections=self.d_model,
356
+ dim=-1,
357
+ )
358
+ return weight * self.norm(input) + bias
359
+
360
+
361
+ def _get_clones(module, N):
362
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
GPT_SoVITS/AR/modules/transformer_onnx.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_onnx 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,
35
+ ) -> None:
36
+ factory_kwargs = {"device": device, "dtype": dtype}
37
+ super(LayerNorm, self).__init__()
38
+ if isinstance(normalized_shape, numbers.Integral):
39
+ # mypy error: incompatible types in assignment
40
+ normalized_shape = (normalized_shape,) # type: ignore[assignment]
41
+ self.normalized_shape = tuple(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(torch.empty(self.normalized_shape, **factory_kwargs))
46
+ self.bias = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
47
+ else:
48
+ self.register_parameter("weight", None)
49
+ self.register_parameter("bias", None)
50
+
51
+ self.reset_parameters()
52
+
53
+ def reset_parameters(self) -> None:
54
+ if self.elementwise_affine:
55
+ nn.init.ones_(self.weight)
56
+ nn.init.zeros_(self.bias)
57
+
58
+ def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
59
+ if isinstance(input, tuple):
60
+ input, embedding = input
61
+ return (
62
+ F.layer_norm(
63
+ input,
64
+ self.normalized_shape,
65
+ self.weight,
66
+ self.bias,
67
+ self.eps,
68
+ ),
69
+ embedding,
70
+ )
71
+
72
+ assert embedding is None
73
+ return F.layer_norm(input, self.normalized_shape, self.weight, self.bias, self.eps)
74
+
75
+ def extra_repr(self) -> str:
76
+ return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
77
+
78
+
79
+ class IdentityNorm(nn.Module):
80
+ def __init__(
81
+ self,
82
+ d_model: int,
83
+ eps: float = 1e-5,
84
+ device=None,
85
+ dtype=None,
86
+ ) -> 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
+
116
+ __constants__ = ["norm"]
117
+
118
+ def __init__(self, encoder_layer, num_layers, norm=None):
119
+ super(TransformerEncoder, self).__init__()
120
+ self.layers = _get_clones(encoder_layer, num_layers)
121
+ self.num_layers = num_layers
122
+ self.norm = norm
123
+
124
+ def forward(
125
+ self,
126
+ src: Tensor,
127
+ mask: Optional[Tensor] = None,
128
+ src_key_padding_mask: Optional[Tensor] = None,
129
+ return_layer_states: bool = False,
130
+ cache=None,
131
+ ) -> Tensor:
132
+ output = src
133
+ for mod in self.layers:
134
+ output = mod(
135
+ output,
136
+ src_mask=mask,
137
+ src_key_padding_mask=src_key_padding_mask,
138
+ cache=cache,
139
+ )
140
+
141
+ if self.norm is not None:
142
+ output = self.norm(output)
143
+
144
+ return output
145
+
146
+
147
+ class TransformerEncoderLayer(nn.Module):
148
+ __constants__ = ["batch_first", "norm_first"]
149
+
150
+ def __init__(
151
+ self,
152
+ d_model: int,
153
+ nhead: int,
154
+ dim_feedforward: int = 2048,
155
+ dropout: float = 0.1,
156
+ activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
157
+ batch_first: bool = False,
158
+ norm_first: bool = False,
159
+ device=None,
160
+ dtype=None,
161
+ linear1_self_attention_cls: nn.Module = nn.Linear,
162
+ linear2_self_attention_cls: nn.Module = nn.Linear,
163
+ linear1_feedforward_cls: nn.Module = nn.Linear,
164
+ linear2_feedforward_cls: nn.Module = nn.Linear,
165
+ layer_norm_cls: nn.Module = LayerNorm,
166
+ layer_norm_eps: float = 1e-5,
167
+ adaptive_layer_norm=False,
168
+ ) -> None:
169
+ factory_kwargs = {"device": device, "dtype": dtype}
170
+ super(TransformerEncoderLayer, self).__init__()
171
+ self.self_attn = MultiheadAttention(
172
+ d_model, # 512 16
173
+ nhead,
174
+ dropout=dropout,
175
+ batch_first=batch_first,
176
+ linear1_cls=linear1_self_attention_cls,
177
+ linear2_cls=linear2_self_attention_cls,
178
+ **factory_kwargs,
179
+ )
180
+ self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
181
+ self.dropout = nn.Dropout(dropout)
182
+ self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
183
+ self.norm_first = norm_first
184
+ self.dropout1 = nn.Dropout(dropout)
185
+ self.dropout2 = nn.Dropout(dropout)
186
+ if isinstance(activation, str):
187
+ activation = _get_activation_fn(activation)
188
+ elif isinstance(activation, partial):
189
+ activation = activation(d_model)
190
+ elif activation == BalancedDoubleSwish:
191
+ activation = BalancedDoubleSwish(d_model)
192
+ self.activation = activation
193
+
194
+ norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
195
+ if layer_norm_cls == IdentityNorm:
196
+ norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
197
+ else:
198
+ norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
199
+
200
+ if adaptive_layer_norm:
201
+ self.norm1 = AdaptiveLayerNorm(d_model, norm1)
202
+ self.norm2 = AdaptiveLayerNorm(d_model, norm2)
203
+ else:
204
+ self.norm1 = norm1
205
+ self.norm2 = norm2
206
+
207
+ def __setstate__(self, state):
208
+ super(TransformerEncoderLayer, self).__setstate__(state)
209
+ if not hasattr(self, "activation"):
210
+ self.activation = F.relu
211
+
212
+ def forward(
213
+ self,
214
+ src: Tensor,
215
+ src_mask: Optional[Tensor] = None,
216
+ src_key_padding_mask: Optional[Tensor] = None,
217
+ cache=None,
218
+ ) -> Tensor:
219
+ x = src
220
+ stage_embedding = None
221
+ x = self.norm1(
222
+ x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
223
+ stage_embedding,
224
+ )
225
+ x = self.norm2(x + self._ff_block(x), stage_embedding)
226
+
227
+ return x
228
+
229
+ def _sa_block(
230
+ self,
231
+ x: Tensor,
232
+ attn_mask: Optional[Tensor],
233
+ key_padding_mask: Optional[Tensor],
234
+ cache=None,
235
+ ) -> Tensor:
236
+ x = self.self_attn(
237
+ x,
238
+ x,
239
+ x,
240
+ attn_mask=attn_mask,
241
+ key_padding_mask=key_padding_mask,
242
+ need_weights=False,
243
+ cache=cache,
244
+ )
245
+ return self.dropout1(x)
246
+
247
+ def _ff_block(self, x: Tensor) -> Tensor:
248
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
249
+ return self.dropout2(x)
250
+
251
+
252
+ class AdaptiveLayerNorm(nn.Module):
253
+ r"""Adaptive Layer Normalization"""
254
+
255
+ def __init__(self, d_model, norm) -> None:
256
+ super(AdaptiveLayerNorm, self).__init__()
257
+ self.project_layer = nn.Linear(d_model, 2 * d_model)
258
+ self.norm = norm
259
+ self.d_model = d_model
260
+ self.eps = self.norm.eps
261
+
262
+ def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
263
+ if isinstance(input, tuple):
264
+ input, embedding = input
265
+ weight, bias = torch.split(
266
+ self.project_layer(embedding),
267
+ split_size_or_sections=self.d_model,
268
+ dim=-1,
269
+ )
270
+ return (weight * self.norm(input) + bias, embedding)
271
+
272
+ weight, bias = torch.split(
273
+ self.project_layer(embedding),
274
+ split_size_or_sections=self.d_model,
275
+ dim=-1,
276
+ )
277
+ return weight * self.norm(input) + bias
278
+
279
+
280
+ def _get_clones(module, N):
281
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
GPT_SoVITS/AR/text_processing/__init__.py ADDED
File without changes
GPT_SoVITS/AR/text_processing/phonemizer.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/phonemizer.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ import itertools
4
+ import re
5
+ from typing import Dict
6
+ from typing import List
7
+
8
+ import regex
9
+ from gruut import sentences
10
+ from gruut.const import Sentence
11
+ from gruut.const import Word
12
+ from AR.text_processing.symbols import SYMBOL_TO_ID
13
+
14
+
15
+ class GruutPhonemizer:
16
+ def __init__(self, language: str):
17
+ self._phonemizer = sentences
18
+ self.lang = language
19
+ self.symbol_to_id = SYMBOL_TO_ID
20
+ self._special_cases_dict: Dict[str] = {
21
+ r"\.\.\.": "... ",
22
+ ";": "; ",
23
+ ":": ": ",
24
+ ",": ", ",
25
+ r"\.": ". ",
26
+ "!": "! ",
27
+ r"\?": "? ",
28
+ "—": "—",
29
+ "…": "… ",
30
+ "«": "«",
31
+ "»": "»",
32
+ }
33
+ self._punctuation_regexp: str = rf"([{''.join(self._special_cases_dict.keys())}])"
34
+
35
+ def _normalize_punctuation(self, text: str) -> str:
36
+ text = regex.sub(rf"\pZ+{self._punctuation_regexp}", r"\1", text)
37
+ text = regex.sub(rf"{self._punctuation_regexp}(\pL)", r"\1 \2", text)
38
+ text = regex.sub(r"\pZ+", r" ", text)
39
+ return text.strip()
40
+
41
+ def _convert_punctuation(self, word: Word) -> str:
42
+ if not word.phonemes:
43
+ return ""
44
+ if word.phonemes[0] in ["‖", "|"]:
45
+ return word.text.strip()
46
+
47
+ phonemes = "".join(word.phonemes)
48
+ # remove modifier characters ˈˌː with regex
49
+ phonemes = re.sub(r"[ˈˌː͡]", "", phonemes)
50
+ return phonemes.strip()
51
+
52
+ def phonemize(self, text: str, espeak: bool = False) -> str:
53
+ text_to_phonemize: str = self._normalize_punctuation(text)
54
+ sents: List[Sentence] = [sent for sent in self._phonemizer(text_to_phonemize, lang="en-us", espeak=espeak)]
55
+ words: List[str] = [self._convert_punctuation(word) for word in itertools.chain(*sents)]
56
+ return " ".join(words)
57
+
58
+ def transform(self, phonemes):
59
+ # convert phonemes to ids
60
+ # dictionary is in symbols.py
61
+ return [self.symbol_to_id[p] for p in phonemes if p in self.symbol_to_id.keys()]
62
+
63
+
64
+ if __name__ == "__main__":
65
+ phonemizer = GruutPhonemizer("en-us")
66
+ # text -> IPA
67
+ phonemes = phonemizer.phonemize("Hello, wor-ld ?")
68
+ print("phonemes:", phonemes)
69
+ print("len(phonemes):", len(phonemes))
70
+ phoneme_ids = phonemizer.transform(phonemes)
71
+ print("phoneme_ids:", phoneme_ids)
72
+ print("len(phoneme_ids):", len(phoneme_ids))
GPT_SoVITS/AR/text_processing/symbols.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/symbols.py
2
+ # reference: https://github.com/lifeiteng/vall-e
3
+ PAD = "_"
4
+ PUNCTUATION = ';:,.!?¡¿—…"«»“” '
5
+ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
6
+ IPA_LETTERS = (
7
+ "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
8
+ )
9
+ SYMBOLS = [PAD] + list(PUNCTUATION) + list(LETTERS) + list(IPA_LETTERS)
10
+ SPACE_ID = SYMBOLS.index(" ")
11
+ SYMBOL_TO_ID = {s: i for i, s in enumerate(SYMBOLS)}
12
+ ID_TO_SYMBOL = {i: s for i, s in enumerate(SYMBOLS)}
GPT_SoVITS/AR/utils/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(extracted_info, key=lambda x: (x[0], x[1]), reverse=True)
22
+ # 获取最新的 ckpt 文件名
23
+ newest_ckpt = sorted_info[0][2]
24
+ return newest_ckpt
25
+
26
+
27
+ # 文本存在且不为空时 return True
28
+ def check_txt_file(file_path):
29
+ try:
30
+ with open(file_path, "r") as file:
31
+ text = file.readline().strip()
32
+ assert text.strip() != ""
33
+ return text
34
+ except Exception:
35
+ return False
36
+ return False
GPT_SoVITS/AR/utils/initialize.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Initialize modules for espnet2 neural networks."""
3
+
4
+ import torch
5
+ from typeguard import check_argument_types
6
+
7
+
8
+ def initialize(model: torch.nn.Module, init: str):
9
+ """Initialize weights of a neural network module.
10
+
11
+ Parameters are initialized using the given method or distribution.
12
+
13
+ Custom initialization routines can be implemented into submodules
14
+ as function `espnet_initialization_fn` within the custom module.
15
+
16
+ Args:
17
+ model: Target.
18
+ init: Method of initialization.
19
+ """
20
+ assert check_argument_types()
21
+ print("init with", init)
22
+
23
+ # weight init
24
+ for p in model.parameters():
25
+ if p.dim() > 1:
26
+ if init == "xavier_uniform":
27
+ torch.nn.init.xavier_uniform_(p.data)
28
+ elif init == "xavier_normal":
29
+ torch.nn.init.xavier_normal_(p.data)
30
+ elif init == "kaiming_uniform":
31
+ torch.nn.init.kaiming_uniform_(p.data, nonlinearity="relu")
32
+ elif init == "kaiming_normal":
33
+ torch.nn.init.kaiming_normal_(p.data, nonlinearity="relu")
34
+ else:
35
+ raise ValueError("Unknown initialization: " + init)
36
+ # bias init
37
+ for name, p in model.named_parameters():
38
+ if ".bias" in name and p.dim() == 1:
39
+ p.data.zero_()
GPT_SoVITS/AR/utils/io.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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) if not name.startswith("_"))
22
+ with open(path, "a") as args_file:
23
+ args_file.write("==> torch version: {}\n".format(torch.__version__))
24
+ args_file.write("==> cudnn version: {}\n".format(torch.backends.cudnn.version()))
25
+ args_file.write("==> Cmd:\n")
26
+ args_file.write(str(sys.argv))
27
+ args_file.write("\n==> args:\n")
28
+ for k, v in sorted(args_dict.items()):
29
+ args_file.write(" %s: %s\n" % (str(k), str(v)))
30
+ args_file.close()
GPT_SoVITS/feature_extractor/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from . import cnhubert, whisper_enc
2
+
3
+ content_module_map = {"cnhubert": cnhubert, "whisper": whisper_enc}
GPT_SoVITS/feature_extractor/cnhubert.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ from transformers import logging as tf_logging
4
+
5
+ tf_logging.set_verbosity_error()
6
+
7
+ import logging
8
+
9
+ logging.getLogger("numba").setLevel(logging.WARNING)
10
+
11
+ from transformers import (
12
+ Wav2Vec2FeatureExtractor,
13
+ HubertModel,
14
+ )
15
+
16
+ import utils
17
+ import torch.nn as nn
18
+
19
+ cnhubert_base_path = None
20
+
21
+
22
+ class CNHubert(nn.Module):
23
+ def __init__(self, base_path: str = None):
24
+ super().__init__()
25
+ if base_path is None:
26
+ base_path = cnhubert_base_path
27
+ if os.path.exists(base_path):
28
+ ...
29
+ else:
30
+ raise FileNotFoundError(base_path)
31
+ self.model = HubertModel.from_pretrained(base_path, local_files_only=True)
32
+ self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(base_path, local_files_only=True)
33
+
34
+ def forward(self, x):
35
+ input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
36
+ feats = self.model(input_values)["last_hidden_state"]
37
+ return feats
38
+
39
+
40
+ # class CNHubertLarge(nn.Module):
41
+ # def __init__(self):
42
+ # super().__init__()
43
+ # self.model = HubertModel.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
44
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
45
+ # def forward(self, x):
46
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
47
+ # feats = self.model(input_values)["last_hidden_state"]
48
+ # return feats
49
+ #
50
+ # class CVec(nn.Module):
51
+ # def __init__(self):
52
+ # super().__init__()
53
+ # self.model = HubertModel.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
54
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
55
+ # def forward(self, x):
56
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
57
+ # feats = self.model(input_values)["last_hidden_state"]
58
+ # return feats
59
+ #
60
+ # class cnw2v2base(nn.Module):
61
+ # def __init__(self):
62
+ # super().__init__()
63
+ # self.model = Wav2Vec2Model.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
64
+ # self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
65
+ # def forward(self, x):
66
+ # input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
67
+ # feats = self.model(input_values)["last_hidden_state"]
68
+ # return feats
69
+
70
+
71
+ def get_model():
72
+ model = CNHubert()
73
+ model.eval()
74
+ return model
75
+
76
+
77
+ # def get_large_model():
78
+ # model = CNHubertLarge()
79
+ # model.eval()
80
+ # return model
81
+ #
82
+ # def get_model_cvec():
83
+ # model = CVec()
84
+ # model.eval()
85
+ # return model
86
+ #
87
+ # def get_model_cnw2v2base():
88
+ # model = cnw2v2base()
89
+ # model.eval()
90
+ # return model
91
+
92
+
93
+ def get_content(hmodel, wav_16k_tensor):
94
+ with torch.no_grad():
95
+ feats = hmodel(wav_16k_tensor)
96
+ return feats.transpose(1, 2)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ model = get_model()
101
+ src_path = "/Users/Shared/原音频2.wav"
102
+ wav_16k_tensor = utils.load_wav_to_torch_and_resample(src_path, 16000)
103
+ model = model
104
+ wav_16k_tensor = wav_16k_tensor
105
+ feats = get_content(model, wav_16k_tensor)
106
+ print(feats.shape)
GPT_SoVITS/feature_extractor/whisper_enc.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_model():
5
+ import whisper
6
+
7
+ model = whisper.load_model("small", device="cpu")
8
+
9
+ return model.encoder
10
+
11
+
12
+ def get_content(model=None, wav_16k_tensor=None):
13
+ from whisper import log_mel_spectrogram, pad_or_trim
14
+
15
+ dev = next(model.parameters()).device
16
+ mel = log_mel_spectrogram(wav_16k_tensor).to(dev)[:, :3000]
17
+ # if torch.cuda.is_available():
18
+ # mel = mel.to(torch.float16)
19
+ feature_len = mel.shape[-1] // 2
20
+ assert mel.shape[-1] < 3000, "输入音频过长,只允许输入30以内音频"
21
+ with torch.no_grad():
22
+ feature = model(pad_or_trim(mel, 3000).unsqueeze(0))[:1, :feature_len, :].transpose(1, 2)
23
+ return feature
GPT_SoVITS/module/__init__.py ADDED
File without changes
GPT_SoVITS/module/attentions.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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__(
12
+ self,
13
+ hidden_channels,
14
+ filter_channels,
15
+ n_heads,
16
+ n_layers,
17
+ kernel_size=1,
18
+ p_dropout=0.0,
19
+ window_size=4,
20
+ isflow=False,
21
+ **kwargs,
22
+ ):
23
+ super().__init__()
24
+ self.hidden_channels = hidden_channels
25
+ self.filter_channels = filter_channels
26
+ self.n_heads = n_heads
27
+ self.n_layers = n_layers
28
+ self.kernel_size = kernel_size
29
+ self.p_dropout = p_dropout
30
+ self.window_size = window_size
31
+
32
+ self.drop = nn.Dropout(p_dropout)
33
+ self.attn_layers = nn.ModuleList()
34
+ self.norm_layers_1 = nn.ModuleList()
35
+ self.ffn_layers = nn.ModuleList()
36
+ self.norm_layers_2 = nn.ModuleList()
37
+ for i in range(self.n_layers):
38
+ self.attn_layers.append(
39
+ MultiHeadAttention(
40
+ hidden_channels,
41
+ hidden_channels,
42
+ n_heads,
43
+ p_dropout=p_dropout,
44
+ window_size=window_size,
45
+ )
46
+ )
47
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
48
+ self.ffn_layers.append(
49
+ FFN(
50
+ hidden_channels,
51
+ hidden_channels,
52
+ filter_channels,
53
+ kernel_size,
54
+ p_dropout=p_dropout,
55
+ )
56
+ )
57
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
58
+ if isflow:
59
+ cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1)
60
+ self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
61
+ self.cond_layer = weight_norm_modules(cond_layer, name="weight")
62
+ self.gin_channels = kwargs["gin_channels"]
63
+
64
+ def forward(self, x, x_mask, g=None):
65
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
66
+ x = x * x_mask
67
+ if g is not None:
68
+ g = self.cond_layer(g)
69
+
70
+ for i in range(self.n_layers):
71
+ if g is not None:
72
+ x = self.cond_pre(x)
73
+ cond_offset = i * 2 * self.hidden_channels
74
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
75
+ x = commons.fused_add_tanh_sigmoid_multiply(x, g_l, torch.IntTensor([self.hidden_channels]))
76
+ y = self.attn_layers[i](x, x, attn_mask)
77
+ y = self.drop(y)
78
+ x = self.norm_layers_1[i](x + y)
79
+
80
+ y = self.ffn_layers[i](x, x_mask)
81
+ y = self.drop(y)
82
+ x = self.norm_layers_2[i](x + y)
83
+ x = x * x_mask
84
+ return x
85
+
86
+
87
+ class Decoder(nn.Module):
88
+ def __init__(
89
+ self,
90
+ hidden_channels,
91
+ filter_channels,
92
+ n_heads,
93
+ n_layers,
94
+ kernel_size=1,
95
+ p_dropout=0.0,
96
+ proximal_bias=False,
97
+ proximal_init=True,
98
+ **kwargs,
99
+ ):
100
+ super().__init__()
101
+ self.hidden_channels = hidden_channels
102
+ self.filter_channels = filter_channels
103
+ self.n_heads = n_heads
104
+ self.n_layers = n_layers
105
+ self.kernel_size = kernel_size
106
+ self.p_dropout = p_dropout
107
+ self.proximal_bias = proximal_bias
108
+ self.proximal_init = proximal_init
109
+
110
+ self.drop = nn.Dropout(p_dropout)
111
+ self.self_attn_layers = nn.ModuleList()
112
+ self.norm_layers_0 = nn.ModuleList()
113
+ self.encdec_attn_layers = nn.ModuleList()
114
+ self.norm_layers_1 = nn.ModuleList()
115
+ self.ffn_layers = nn.ModuleList()
116
+ self.norm_layers_2 = nn.ModuleList()
117
+ for i in range(self.n_layers):
118
+ self.self_attn_layers.append(
119
+ MultiHeadAttention(
120
+ hidden_channels,
121
+ hidden_channels,
122
+ n_heads,
123
+ p_dropout=p_dropout,
124
+ proximal_bias=proximal_bias,
125
+ proximal_init=proximal_init,
126
+ )
127
+ )
128
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
129
+ self.encdec_attn_layers.append(
130
+ MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)
131
+ )
132
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
133
+ self.ffn_layers.append(
134
+ FFN(
135
+ hidden_channels,
136
+ hidden_channels,
137
+ filter_channels,
138
+ kernel_size,
139
+ p_dropout=p_dropout,
140
+ causal=True,
141
+ )
142
+ )
143
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
144
+
145
+ def forward(self, x, x_mask, h, h_mask):
146
+ """
147
+ x: decoder input
148
+ h: encoder output
149
+ """
150
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
151
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
152
+ x = x * x_mask
153
+ for i in range(self.n_layers):
154
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
155
+ y = self.drop(y)
156
+ x = self.norm_layers_0[i](x + y)
157
+
158
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
159
+ y = self.drop(y)
160
+ x = self.norm_layers_1[i](x + y)
161
+
162
+ y = self.ffn_layers[i](x, x_mask)
163
+ y = self.drop(y)
164
+ x = self.norm_layers_2[i](x + y)
165
+ x = x * x_mask
166
+ return x
167
+
168
+
169
+ class MultiHeadAttention(nn.Module):
170
+ def __init__(
171
+ self,
172
+ channels,
173
+ out_channels,
174
+ n_heads,
175
+ p_dropout=0.0,
176
+ window_size=None,
177
+ heads_share=True,
178
+ block_length=None,
179
+ proximal_bias=False,
180
+ proximal_init=False,
181
+ ):
182
+ super().__init__()
183
+ assert channels % n_heads == 0
184
+
185
+ self.channels = channels
186
+ self.out_channels = out_channels
187
+ self.n_heads = n_heads
188
+ self.p_dropout = p_dropout
189
+ self.window_size = window_size
190
+ self.heads_share = heads_share
191
+ self.block_length = block_length
192
+ self.proximal_bias = proximal_bias
193
+ self.proximal_init = proximal_init
194
+ self.attn = None
195
+
196
+ self.k_channels = channels // n_heads
197
+ self.conv_q = nn.Conv1d(channels, channels, 1)
198
+ self.conv_k = nn.Conv1d(channels, channels, 1)
199
+ self.conv_v = nn.Conv1d(channels, channels, 1)
200
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
201
+ self.drop = nn.Dropout(p_dropout)
202
+
203
+ if window_size is not None:
204
+ n_heads_rel = 1 if heads_share else n_heads
205
+ rel_stddev = self.k_channels**-0.5
206
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
207
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
208
+
209
+ nn.init.xavier_uniform_(self.conv_q.weight)
210
+ nn.init.xavier_uniform_(self.conv_k.weight)
211
+ nn.init.xavier_uniform_(self.conv_v.weight)
212
+ if proximal_init:
213
+ with torch.no_grad():
214
+ self.conv_k.weight.copy_(self.conv_q.weight)
215
+ self.conv_k.bias.copy_(self.conv_q.bias)
216
+
217
+ def forward(self, x, c, attn_mask=None):
218
+ q = self.conv_q(x)
219
+ k = self.conv_k(c)
220
+ v = self.conv_v(c)
221
+
222
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
223
+
224
+ x = self.conv_o(x)
225
+ return x
226
+
227
+ def attention(self, query, key, value, mask=None):
228
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
229
+ b, d, t_s, t_t = (*key.size(), query.size(2))
230
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
231
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
232
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
233
+
234
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
235
+ if self.window_size is not None:
236
+ assert t_s == t_t, "Relative attention is only available for self-attention."
237
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
238
+ rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
239
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
240
+ scores = scores + scores_local
241
+ if self.proximal_bias:
242
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
243
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
244
+ if mask is not None:
245
+ scores = scores.masked_fill(mask == 0, -1e4)
246
+ if self.block_length is not None:
247
+ assert t_s == t_t, "Local attention is only available for self-attention."
248
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
249
+ scores = scores.masked_fill(block_mask == 0, -1e4)
250
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
251
+ p_attn = self.drop(p_attn)
252
+ output = torch.matmul(p_attn, value)
253
+ if self.window_size is not None:
254
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
255
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
256
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
257
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
258
+ return output, p_attn
259
+
260
+ def _matmul_with_relative_values(self, x, y):
261
+ """
262
+ x: [b, h, l, m]
263
+ y: [h or 1, m, d]
264
+ ret: [b, h, l, d]
265
+ """
266
+ ret = torch.matmul(x, y.unsqueeze(0))
267
+ return ret
268
+
269
+ def _matmul_with_relative_keys(self, x, y):
270
+ """
271
+ x: [b, h, l, d]
272
+ y: [h or 1, m, d]
273
+ ret: [b, h, l, m]
274
+ """
275
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
276
+ return ret
277
+
278
+ def _get_relative_embeddings(self, relative_embeddings, length):
279
+ max_relative_position = 2 * self.window_size + 1
280
+ # Pad first before slice to avoid using cond ops.
281
+ pad_length = max(length - (self.window_size + 1), 0)
282
+ slice_start_position = max((self.window_size + 1) - length, 0)
283
+ slice_end_position = slice_start_position + 2 * length - 1
284
+ if pad_length > 0:
285
+ padded_relative_embeddings = F.pad(
286
+ relative_embeddings,
287
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
288
+ )
289
+ else:
290
+ padded_relative_embeddings = relative_embeddings
291
+ used_relative_embeddings = padded_relative_embeddings[:, slice_start_position:slice_end_position]
292
+ return used_relative_embeddings
293
+
294
+ def _relative_position_to_absolute_position(self, x):
295
+ """
296
+ x: [b, h, l, 2*l-1]
297
+ ret: [b, h, l, l]
298
+ """
299
+ batch, heads, length, _ = x.size()
300
+ # Concat columns of pad to shift from relative to absolute indexing.
301
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
302
+
303
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
304
+ x_flat = x.view([batch, heads, length * 2 * length])
305
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]))
306
+
307
+ # Reshape and slice out the padded elements.
308
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[:, :, :length, length - 1 :]
309
+ return x_final
310
+
311
+ def _absolute_position_to_relative_position(self, x):
312
+ """
313
+ x: [b, h, l, l]
314
+ ret: [b, h, l, 2*l-1]
315
+ """
316
+ batch, heads, length, _ = x.size()
317
+ # padd along column
318
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]))
319
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
320
+ # add 0's in the beginning that will skew the elements after reshape
321
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
322
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
323
+ return x_final
324
+
325
+ def _attention_bias_proximal(self, length):
326
+ """Bias for self-attention to encourage attention to close positions.
327
+ Args:
328
+ length: an integer scalar.
329
+ Returns:
330
+ a Tensor with shape [1, 1, length, length]
331
+ """
332
+ r = torch.arange(length, dtype=torch.float32)
333
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
334
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
335
+
336
+
337
+ class FFN(nn.Module):
338
+ def __init__(
339
+ self,
340
+ in_channels,
341
+ out_channels,
342
+ filter_channels,
343
+ kernel_size,
344
+ p_dropout=0.0,
345
+ activation=None,
346
+ causal=False,
347
+ ):
348
+ super().__init__()
349
+ self.in_channels = in_channels
350
+ self.out_channels = out_channels
351
+ self.filter_channels = filter_channels
352
+ self.kernel_size = kernel_size
353
+ self.p_dropout = p_dropout
354
+ self.activation = activation
355
+ self.causal = causal
356
+
357
+ if causal:
358
+ self.padding = self._causal_padding
359
+ else:
360
+ self.padding = self._same_padding
361
+
362
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
363
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
364
+ self.drop = nn.Dropout(p_dropout)
365
+
366
+ def forward(self, x, x_mask):
367
+ x = self.conv_1(self.padding(x * x_mask))
368
+ if self.activation == "gelu":
369
+ x = x * torch.sigmoid(1.702 * x)
370
+ else:
371
+ x = torch.relu(x)
372
+ x = self.drop(x)
373
+ x = self.conv_2(self.padding(x * x_mask))
374
+ return x * x_mask
375
+
376
+ def _causal_padding(self, x):
377
+ if self.kernel_size == 1:
378
+ return x
379
+ pad_l = self.kernel_size - 1
380
+ pad_r = 0
381
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
382
+ x = F.pad(x, commons.convert_pad_shape(padding))
383
+ return x
384
+
385
+ def _same_padding(self, x):
386
+ if self.kernel_size == 1:
387
+ return x
388
+ pad_l = (self.kernel_size - 1) // 2
389
+ pad_r = self.kernel_size // 2
390
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
391
+ x = F.pad(x, commons.convert_pad_shape(padding))
392
+ return x
393
+
394
+
395
+ import torch.nn as nn
396
+ from torch.nn.utils import remove_weight_norm, weight_norm
397
+
398
+
399
+ class Depthwise_Separable_Conv1D(nn.Module):
400
+ def __init__(
401
+ self,
402
+ in_channels,
403
+ out_channels,
404
+ kernel_size,
405
+ stride=1,
406
+ padding=0,
407
+ dilation=1,
408
+ bias=True,
409
+ padding_mode="zeros", # TODO: refine this type
410
+ device=None,
411
+ dtype=None,
412
+ ):
413
+ super().__init__()
414
+ self.depth_conv = nn.Conv1d(
415
+ in_channels=in_channels,
416
+ out_channels=in_channels,
417
+ kernel_size=kernel_size,
418
+ groups=in_channels,
419
+ stride=stride,
420
+ padding=padding,
421
+ dilation=dilation,
422
+ bias=bias,
423
+ padding_mode=padding_mode,
424
+ device=device,
425
+ dtype=dtype,
426
+ )
427
+ self.point_conv = nn.Conv1d(
428
+ in_channels=in_channels,
429
+ out_channels=out_channels,
430
+ kernel_size=1,
431
+ bias=bias,
432
+ device=device,
433
+ dtype=dtype,
434
+ )
435
+
436
+ def forward(self, input):
437
+ return self.point_conv(self.depth_conv(input))
438
+
439
+ def weight_norm(self):
440
+ self.depth_conv = weight_norm(self.depth_conv, name="weight")
441
+ self.point_conv = weight_norm(self.point_conv, name="weight")
442
+
443
+ def remove_weight_norm(self):
444
+ self.depth_conv = remove_weight_norm(self.depth_conv, name="weight")
445
+ self.point_conv = remove_weight_norm(self.point_conv, name="weight")
446
+
447
+
448
+ class Depthwise_Separable_TransposeConv1D(nn.Module):
449
+ def __init__(
450
+ self,
451
+ in_channels,
452
+ out_channels,
453
+ kernel_size,
454
+ stride=1,
455
+ padding=0,
456
+ output_padding=0,
457
+ bias=True,
458
+ dilation=1,
459
+ padding_mode="zeros", # TODO: refine this type
460
+ device=None,
461
+ dtype=None,
462
+ ):
463
+ super().__init__()
464
+ self.depth_conv = nn.ConvTranspose1d(
465
+ in_channels=in_channels,
466
+ out_channels=in_channels,
467
+ kernel_size=kernel_size,
468
+ groups=in_channels,
469
+ stride=stride,
470
+ output_padding=output_padding,
471
+ padding=padding,
472
+ dilation=dilation,
473
+ bias=bias,
474
+ padding_mode=padding_mode,
475
+ device=device,
476
+ dtype=dtype,
477
+ )
478
+ self.point_conv = nn.Conv1d(
479
+ in_channels=in_channels,
480
+ out_channels=out_channels,
481
+ kernel_size=1,
482
+ bias=bias,
483
+ device=device,
484
+ dtype=dtype,
485
+ )
486
+
487
+ def forward(self, input):
488
+ return self.point_conv(self.depth_conv(input))
489
+
490
+ def weight_norm(self):
491
+ self.depth_conv = weight_norm(self.depth_conv, name="weight")
492
+ self.point_conv = weight_norm(self.point_conv, name="weight")
493
+
494
+ def remove_weight_norm(self):
495
+ remove_weight_norm(self.depth_conv, name="weight")
496
+ remove_weight_norm(self.point_conv, name="weight")
497
+
498
+
499
+ def weight_norm_modules(module, name="weight", dim=0):
500
+ if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
501
+ module.weight_norm()
502
+ return module
503
+ else:
504
+ return weight_norm(module, name, dim)
505
+
506
+
507
+ def remove_weight_norm_modules(module, name="weight"):
508
+ if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
509
+ module.remove_weight_norm()
510
+ else:
511
+ remove_weight_norm(module, name)
512
+
513
+
514
+ class FFT(nn.Module):
515
+ def __init__(
516
+ self,
517
+ hidden_channels,
518
+ filter_channels,
519
+ n_heads,
520
+ n_layers=1,
521
+ kernel_size=1,
522
+ p_dropout=0.0,
523
+ proximal_bias=False,
524
+ proximal_init=True,
525
+ isflow=False,
526
+ **kwargs,
527
+ ):
528
+ super().__init__()
529
+ self.hidden_channels = hidden_channels
530
+ self.filter_channels = filter_channels
531
+ self.n_heads = n_heads
532
+ self.n_layers = n_layers
533
+ self.kernel_size = kernel_size
534
+ self.p_dropout = p_dropout
535
+ self.proximal_bias = proximal_bias
536
+ self.proximal_init = proximal_init
537
+ if isflow:
538
+ cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1)
539
+ self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
540
+ self.cond_layer = weight_norm_modules(cond_layer, name="weight")
541
+ self.gin_channels = kwargs["gin_channels"]
542
+ self.drop = nn.Dropout(p_dropout)
543
+ self.self_attn_layers = nn.ModuleList()
544
+ self.norm_layers_0 = nn.ModuleList()
545
+ self.ffn_layers = nn.ModuleList()
546
+ self.norm_layers_1 = nn.ModuleList()
547
+ for i in range(self.n_layers):
548
+ self.self_attn_layers.append(
549
+ MultiHeadAttention(
550
+ hidden_channels,
551
+ hidden_channels,
552
+ n_heads,
553
+ p_dropout=p_dropout,
554
+ proximal_bias=proximal_bias,
555
+ proximal_init=proximal_init,
556
+ )
557
+ )
558
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
559
+ self.ffn_layers.append(
560
+ FFN(
561
+ hidden_channels,
562
+ hidden_channels,
563
+ filter_channels,
564
+ kernel_size,
565
+ p_dropout=p_dropout,
566
+ causal=True,
567
+ )
568
+ )
569
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
570
+
571
+ def forward(self, x, x_mask, g=None):
572
+ """
573
+ x: decoder input
574
+ h: encoder output
575
+ """
576
+ if g is not None:
577
+ g = self.cond_layer(g)
578
+
579
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
580
+ x = x * x_mask
581
+ for i in range(self.n_layers):
582
+ if g is not None:
583
+ x = self.cond_pre(x)
584
+ cond_offset = i * 2 * self.hidden_channels
585
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
586
+ x = commons.fused_add_tanh_sigmoid_multiply(x, g_l, torch.IntTensor([self.hidden_channels]))
587
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
588
+ y = self.drop(y)
589
+ x = self.norm_layers_0[i](x + y)
590
+
591
+ y = self.ffn_layers[i](x, x_mask)
592
+ y = self.drop(y)
593
+ x = self.norm_layers_1[i](x + y)
594
+ x = x * x_mask
595
+ return x
596
+
597
+
598
+ class TransformerCouplingLayer(nn.Module):
599
+ def __init__(
600
+ self,
601
+ channels,
602
+ hidden_channels,
603
+ kernel_size,
604
+ n_layers,
605
+ n_heads,
606
+ p_dropout=0,
607
+ filter_channels=0,
608
+ mean_only=False,
609
+ wn_sharing_parameter=None,
610
+ gin_channels=0,
611
+ ):
612
+ assert channels % 2 == 0, "channels should be divisible by 2"
613
+ super().__init__()
614
+ self.channels = channels
615
+ self.hidden_channels = hidden_channels
616
+ self.kernel_size = kernel_size
617
+ self.n_layers = n_layers
618
+ self.half_channels = channels // 2
619
+ self.mean_only = mean_only
620
+
621
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
622
+ self.enc = (
623
+ Encoder(
624
+ hidden_channels,
625
+ filter_channels,
626
+ n_heads,
627
+ n_layers,
628
+ kernel_size,
629
+ p_dropout,
630
+ isflow=True,
631
+ gin_channels=gin_channels,
632
+ )
633
+ if wn_sharing_parameter is None
634
+ else wn_sharing_parameter
635
+ )
636
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
637
+ self.post.weight.data.zero_()
638
+ self.post.bias.data.zero_()
639
+
640
+ def forward(self, x, x_mask, g=None, reverse=False):
641
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
642
+ h = self.pre(x0) * x_mask
643
+ h = self.enc(h, x_mask, g=g)
644
+ stats = self.post(h) * x_mask
645
+ if not self.mean_only:
646
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
647
+ else:
648
+ m = stats
649
+ logs = torch.zeros_like(m)
650
+
651
+ if not reverse:
652
+ x1 = m + x1 * torch.exp(logs) * x_mask
653
+ x = torch.cat([x0, x1], 1)
654
+ logdet = torch.sum(logs, [1, 2])
655
+ return x, logdet
656
+ else:
657
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
658
+ x = torch.cat([x0, x1], 1)
659
+ return x
GPT_SoVITS/module/attentions_onnx.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ from typing import Optional
9
+
10
+
11
+ class LayerNorm(nn.Module):
12
+ def __init__(self, channels, eps=1e-5):
13
+ super().__init__()
14
+ self.channels = channels
15
+ self.eps = eps
16
+
17
+ self.gamma = nn.Parameter(torch.ones(channels))
18
+ self.beta = nn.Parameter(torch.zeros(channels))
19
+
20
+ def forward(self, x):
21
+ x = x.transpose(1, -1)
22
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
23
+ return x.transpose(1, -1)
24
+
25
+
26
+ @torch.jit.script
27
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
28
+ n_channels_int = n_channels[0]
29
+ in_act = input_a + input_b
30
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
31
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
32
+ acts = t_act * s_act
33
+ return acts
34
+
35
+
36
+ class Encoder(nn.Module):
37
+ def __init__(
38
+ self,
39
+ hidden_channels,
40
+ filter_channels,
41
+ n_heads,
42
+ n_layers,
43
+ kernel_size=1,
44
+ p_dropout=0.0,
45
+ window_size=4,
46
+ isflow=True,
47
+ **kwargs,
48
+ ):
49
+ super().__init__()
50
+ self.hidden_channels = hidden_channels
51
+ self.filter_channels = filter_channels
52
+ self.n_heads = n_heads
53
+ self.n_layers = n_layers
54
+ self.kernel_size = kernel_size
55
+ self.p_dropout = p_dropout
56
+ self.window_size = window_size
57
+ # if isflow:
58
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
59
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
60
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
61
+ # self.gin_channels = 256
62
+ self.cond_layer_idx = self.n_layers
63
+ self.spk_emb_linear = nn.Linear(256, self.hidden_channels)
64
+ if "gin_channels" in kwargs:
65
+ self.gin_channels = kwargs["gin_channels"]
66
+ if self.gin_channels != 0:
67
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
68
+ # vits2 says 3rd block, so idx is 2 by default
69
+ self.cond_layer_idx = kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
70
+ logging.debug(self.gin_channels, self.cond_layer_idx)
71
+ assert self.cond_layer_idx < self.n_layers, "cond_layer_idx should be less than n_layers"
72
+ self.drop = nn.Dropout(p_dropout)
73
+ self.attn_layers = nn.ModuleList()
74
+ self.norm_layers_1 = nn.ModuleList()
75
+ self.ffn_layers = nn.ModuleList()
76
+ self.norm_layers_2 = nn.ModuleList()
77
+ for i in range(self.n_layers):
78
+ self.attn_layers.append(
79
+ MultiHeadAttention(
80
+ hidden_channels,
81
+ hidden_channels,
82
+ n_heads,
83
+ p_dropout=p_dropout,
84
+ window_size=window_size,
85
+ )
86
+ )
87
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
88
+ self.ffn_layers.append(
89
+ FFN(
90
+ hidden_channels,
91
+ hidden_channels,
92
+ filter_channels,
93
+ kernel_size,
94
+ p_dropout=p_dropout,
95
+ )
96
+ )
97
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
98
+
99
+ # def forward(self, x, x_mask, g=None):
100
+ # attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
101
+ # x = x * x_mask
102
+ # for i in range(self.n_layers):
103
+ # if i == self.cond_layer_idx and g is not None:
104
+ # g = self.spk_emb_linear(g.transpose(1, 2))
105
+ # g = g.transpose(1, 2)
106
+ # x = x + g
107
+ # x = x * x_mask
108
+ # y = self.attn_layers[i](x, x, attn_mask)
109
+ # y = self.drop(y)
110
+ # x = self.norm_layers_1[i](x + y)
111
+
112
+ # y = self.ffn_layers[i](x, x_mask)
113
+ # y = self.drop(y)
114
+ # x = self.norm_layers_2[i](x + y)
115
+ # x = x * x_mask
116
+ # return x
117
+
118
+ def forward(self, x, x_mask):
119
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
120
+ x = x * x_mask
121
+ for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zip(
122
+ self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2
123
+ ):
124
+ y = attn_layers(x, x, attn_mask)
125
+ y = self.drop(y)
126
+ x = norm_layers_1(x + y)
127
+
128
+ y = ffn_layers(x, x_mask)
129
+ y = self.drop(y)
130
+ x = norm_layers_2(x + y)
131
+ x = x * x_mask
132
+ return x
133
+
134
+
135
+ class MultiHeadAttention(nn.Module):
136
+ def __init__(
137
+ self,
138
+ channels,
139
+ out_channels,
140
+ n_heads,
141
+ p_dropout=0.0,
142
+ window_size=None,
143
+ heads_share=True,
144
+ block_length=None,
145
+ proximal_bias=False,
146
+ proximal_init=False,
147
+ ):
148
+ super().__init__()
149
+ assert channels % n_heads == 0
150
+
151
+ self.channels = channels
152
+ self.out_channels = out_channels
153
+ self.n_heads = n_heads
154
+ self.p_dropout = p_dropout
155
+ self.window_size = window_size
156
+ self.heads_share = heads_share
157
+ self.block_length = block_length
158
+ self.proximal_bias = proximal_bias
159
+ self.proximal_init = proximal_init
160
+ self.attn = None
161
+
162
+ self.k_channels = channels // n_heads
163
+ self.conv_q = nn.Conv1d(channels, channels, 1)
164
+ self.conv_k = nn.Conv1d(channels, channels, 1)
165
+ self.conv_v = nn.Conv1d(channels, channels, 1)
166
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
167
+ self.drop = nn.Dropout(p_dropout)
168
+
169
+ if window_size is not None:
170
+ n_heads_rel = 1 if heads_share else n_heads
171
+ rel_stddev = self.k_channels**-0.5
172
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
173
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
174
+
175
+ nn.init.xavier_uniform_(self.conv_q.weight)
176
+ nn.init.xavier_uniform_(self.conv_k.weight)
177
+ nn.init.xavier_uniform_(self.conv_v.weight)
178
+ if proximal_init:
179
+ with torch.no_grad():
180
+ self.conv_k.weight.copy_(self.conv_q.weight)
181
+ self.conv_k.bias.copy_(self.conv_q.bias)
182
+
183
+ def forward(self, x, c, attn_mask: Optional[torch.Tensor] = None):
184
+ q = self.conv_q(x)
185
+ k = self.conv_k(c)
186
+ v = self.conv_v(c)
187
+
188
+ # x, self.attn = self.attention(q, k, v, mask=attn_mask)
189
+ x, _ = self.attention(q, k, v, mask=attn_mask)
190
+
191
+ x = self.conv_o(x)
192
+ return x
193
+
194
+ def attention(self, query, key, value, mask: Optional[torch.Tensor] = None):
195
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
196
+ b, d, t_s, _ = (*key.size(), query.size(2))
197
+ query = query.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
198
+ key = key.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
199
+ value = value.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
200
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
201
+
202
+ if self.window_size is not None:
203
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
204
+ rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
205
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
206
+ scores = scores + scores_local
207
+
208
+ if mask is not None:
209
+ scores = scores.masked_fill(mask == 0, -1e4)
210
+
211
+ p_attn = F.softmax(scores, dim=-1)
212
+ p_attn = self.drop(p_attn)
213
+ output = torch.matmul(p_attn, value)
214
+
215
+ if self.window_size is not None:
216
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
217
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
218
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
219
+
220
+ output = output.transpose(2, 3).contiguous().view(b, d, -1)
221
+ return output, p_attn
222
+
223
+ def _matmul_with_relative_values(self, x, y):
224
+ """
225
+ x: [b, h, l, m]
226
+ y: [h or 1, m, d]
227
+ ret: [b, h, l, d]
228
+ """
229
+ ret = torch.matmul(x, y.unsqueeze(0))
230
+ return ret
231
+
232
+ def _matmul_with_relative_keys(self, x, y):
233
+ """
234
+ x: [b, h, l, d]
235
+ y: [h or 1, m, d]
236
+ ret: [b, h, l, m]
237
+ """
238
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
239
+ return ret
240
+
241
+ def _get_relative_embeddings(self, relative_embeddings, length):
242
+ max_relative_position = 2 * self.window_size + 1
243
+ # Pad first before slice to avoid using cond ops.
244
+ pad_l = torch.zeros((1), dtype=torch.int64) + length - (self.window_size + 1)
245
+ pad_s = torch.zeros((1), dtype=torch.int64) + (self.window_size + 1) - length
246
+ pad_length = torch.max(pad_l, other=torch.zeros((1), dtype=torch.int64))
247
+ slice_start_position = torch.max(pad_s, other=torch.zeros((1), dtype=torch.int64))
248
+
249
+ slice_end_position = slice_start_position + 2 * length - 1
250
+ padded_relative_embeddings = F.pad(
251
+ relative_embeddings,
252
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
253
+ )
254
+ used_relative_embeddings = padded_relative_embeddings[:, slice_start_position:slice_end_position]
255
+ return used_relative_embeddings
256
+
257
+ def _relative_position_to_absolute_position(self, x):
258
+ """
259
+ x: [b, h, l, 2*l-1]
260
+ ret: [b, h, l, l]
261
+ """
262
+ batch, heads, length, _ = x.size()
263
+ # Concat columns of pad to shift from relative to absolute indexing.
264
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
265
+
266
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
267
+ x_flat = x.view([batch, heads, length * 2 * length])
268
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]))
269
+
270
+ # Reshape and slice out the padded elements.
271
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[:, :, :length, length - 1 :]
272
+ return x_final
273
+
274
+ def _absolute_position_to_relative_position(self, x):
275
+ """
276
+ x: [b, h, l, l]
277
+ ret: [b, h, l, 2*l-1]
278
+ """
279
+ batch, heads, length, _ = x.size()
280
+ # padd along column
281
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]))
282
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
283
+ # add 0's in the beginning that will skew the elements after reshape
284
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
285
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
286
+ return x_final
287
+
288
+ def _attention_bias_proximal(self, length):
289
+ """Bias for self-attention to encourage attention to close positions.
290
+ Args:
291
+ length: an integer scalar.
292
+ Returns:
293
+ a Tensor with shape [1, 1, length, length]
294
+ """
295
+ r = torch.arange(length, dtype=torch.float32)
296
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
297
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
298
+
299
+
300
+ class FFN(nn.Module):
301
+ def __init__(
302
+ self,
303
+ in_channels,
304
+ out_channels,
305
+ filter_channels,
306
+ kernel_size,
307
+ p_dropout=0.0,
308
+ activation="",
309
+ causal=False,
310
+ ):
311
+ super().__init__()
312
+ self.in_channels = in_channels
313
+ self.out_channels = out_channels
314
+ self.filter_channels = filter_channels
315
+ self.kernel_size = kernel_size
316
+ self.p_dropout = p_dropout
317
+ self.activation = activation
318
+ self.causal = causal
319
+
320
+ # 从上下文看这里一定是 False
321
+ # if causal:
322
+ # self.padding = self._causal_padding
323
+ # else:
324
+ # self.padding = self._same_padding
325
+
326
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
327
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
328
+ self.drop = nn.Dropout(p_dropout)
329
+
330
+ def forward(self, x, x_mask):
331
+ x = self.conv_1(self.padding(x * x_mask))
332
+ if self.activation == "gelu":
333
+ x = x * torch.sigmoid(1.702 * x)
334
+ else:
335
+ x = torch.relu(x)
336
+ x = self.drop(x)
337
+ x = self.conv_2(self.padding(x * x_mask))
338
+ return x * x_mask
339
+
340
+ def padding(self, x):
341
+ return self._same_padding(x)
342
+
343
+ def _causal_padding(self, x):
344
+ if self.kernel_size == 1:
345
+ return x
346
+ pad_l = self.kernel_size - 1
347
+ pad_r = 0
348
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
349
+ x = F.pad(x, commons.convert_pad_shape(padding))
350
+ return x
351
+
352
+ def _same_padding(self, x):
353
+ if self.kernel_size == 1:
354
+ return x
355
+ pad_l = (self.kernel_size - 1) // 2
356
+ pad_r = self.kernel_size // 2
357
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
358
+ x = F.pad(x, commons.convert_pad_shape(padding))
359
+ return x
360
+
361
+
362
+ class MRTE(nn.Module):
363
+ def __init__(
364
+ self,
365
+ content_enc_channels=192,
366
+ hidden_size=512,
367
+ out_channels=192,
368
+ kernel_size=5,
369
+ n_heads=4,
370
+ ge_layer=2,
371
+ ):
372
+ super(MRTE, self).__init__()
373
+ self.cross_attention = MultiHeadAttention(hidden_size, hidden_size, n_heads)
374
+ self.c_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
375
+ self.text_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
376
+ self.c_post = nn.Conv1d(hidden_size, out_channels, 1)
377
+
378
+ def forward(self, ssl_enc, ssl_mask, text, text_mask, ge):
379
+ attn_mask = text_mask.unsqueeze(2) * ssl_mask.unsqueeze(-1)
380
+
381
+ ssl_enc = self.c_pre(ssl_enc * ssl_mask)
382
+ text_enc = self.text_pre(text * text_mask)
383
+ x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
384
+ x = self.c_post(x * ssl_mask)
385
+ return x
GPT_SoVITS/module/commons.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+
6
+ def init_weights(m, mean=0.0, std=0.01):
7
+ classname = m.__class__.__name__
8
+ if classname.find("Conv") != -1:
9
+ m.weight.data.normal_(mean, std)
10
+
11
+
12
+ def get_padding(kernel_size, dilation=1):
13
+ return int((kernel_size * dilation - dilation) / 2)
14
+
15
+
16
+ # def convert_pad_shape(pad_shape):
17
+ # l = pad_shape[::-1]
18
+ # pad_shape = [item for sublist in l for item in sublist]
19
+ # return pad_shape
20
+
21
+
22
+ def intersperse(lst, item):
23
+ result = [item] * (len(lst) * 2 + 1)
24
+ result[1::2] = lst
25
+ return result
26
+
27
+
28
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
29
+ """KL(P||Q)"""
30
+ kl = (logs_q - logs_p) - 0.5
31
+ kl += 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
32
+ return kl
33
+
34
+
35
+ def rand_gumbel(shape):
36
+ """Sample from the Gumbel distribution, protect from overflows."""
37
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
38
+ return -torch.log(-torch.log(uniform_samples))
39
+
40
+
41
+ def rand_gumbel_like(x):
42
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
43
+ return g
44
+
45
+
46
+ def slice_segments(x, ids_str, segment_size=4):
47
+ ret = torch.zeros_like(x[:, :, :segment_size])
48
+ for i in range(x.size(0)):
49
+ idx_str = ids_str[i]
50
+ idx_end = idx_str + segment_size
51
+ ret[i] = x[i, :, idx_str:idx_end]
52
+ return ret
53
+
54
+
55
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
56
+ b, d, t = x.size()
57
+ if x_lengths is None:
58
+ x_lengths = t
59
+ ids_str_max = x_lengths - segment_size + 1
60
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
61
+ ret = slice_segments(x, ids_str, segment_size)
62
+ return ret, ids_str
63
+
64
+
65
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
66
+ position = torch.arange(length, dtype=torch.float)
67
+ num_timescales = channels // 2
68
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (num_timescales - 1)
69
+ inv_timescales = min_timescale * torch.exp(
70
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
71
+ )
72
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
73
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
74
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
75
+ signal = signal.view(1, channels, length)
76
+ return signal
77
+
78
+
79
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
80
+ b, channels, length = x.size()
81
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
82
+ return x + signal.to(dtype=x.dtype, device=x.device)
83
+
84
+
85
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
86
+ b, channels, length = x.size()
87
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
88
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
89
+
90
+
91
+ def subsequent_mask(length):
92
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
93
+ return mask
94
+
95
+
96
+ @torch.jit.script
97
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
98
+ n_channels_int = n_channels[0]
99
+ in_act = input_a + input_b
100
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
101
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
102
+ acts = t_act * s_act
103
+ return acts
104
+
105
+
106
+ def convert_pad_shape(pad_shape):
107
+ l = pad_shape[::-1]
108
+ pad_shape = [item for sublist in l for item in sublist]
109
+ return pad_shape
110
+
111
+
112
+ def shift_1d(x):
113
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
114
+ return x
115
+
116
+
117
+ def sequence_mask(length, max_length=None):
118
+ if max_length is None:
119
+ max_length = length.max()
120
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
121
+ return x.unsqueeze(0) < length.unsqueeze(1)
122
+
123
+
124
+ def generate_path(duration, mask):
125
+ """
126
+ duration: [b, 1, t_x]
127
+ mask: [b, 1, t_y, t_x]
128
+ """
129
+ device = duration.device
130
+
131
+ b, _, t_y, t_x = mask.shape
132
+ cum_duration = torch.cumsum(duration, -1)
133
+
134
+ cum_duration_flat = cum_duration.view(b * t_x)
135
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
136
+ path = path.view(b, t_x, t_y)
137
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
138
+ path = path.unsqueeze(1).transpose(2, 3) * mask
139
+ return path
140
+
141
+
142
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
143
+ if isinstance(parameters, torch.Tensor):
144
+ parameters = [parameters]
145
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
146
+ norm_type = float(norm_type)
147
+ if clip_value is not None:
148
+ clip_value = float(clip_value)
149
+
150
+ total_norm = 0
151
+ for p in parameters:
152
+ param_norm = p.grad.data.norm(norm_type)
153
+ total_norm += param_norm.item() ** norm_type
154
+ if clip_value is not None:
155
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
156
+ total_norm = total_norm ** (1.0 / norm_type)
157
+ return total_norm
158
+
159
+
160
+ def squeeze(x, x_mask=None, n_sqz=2):
161
+ b, c, t = x.size()
162
+
163
+ t = (t // n_sqz) * n_sqz
164
+ x = x[:, :, :t]
165
+ x_sqz = x.view(b, c, t // n_sqz, n_sqz)
166
+ x_sqz = x_sqz.permute(0, 3, 1, 2).contiguous().view(b, c * n_sqz, t // n_sqz)
167
+
168
+ if x_mask is not None:
169
+ x_mask = x_mask[:, :, n_sqz - 1 :: n_sqz]
170
+ else:
171
+ x_mask = torch.ones(b, 1, t // n_sqz).to(device=x.device, dtype=x.dtype)
172
+ return x_sqz * x_mask, x_mask
173
+
174
+
175
+ def unsqueeze(x, x_mask=None, n_sqz=2):
176
+ b, c, t = x.size()
177
+
178
+ x_unsqz = x.view(b, n_sqz, c // n_sqz, t)
179
+ x_unsqz = x_unsqz.permute(0, 2, 3, 1).contiguous().view(b, c // n_sqz, t * n_sqz)
180
+
181
+ if x_mask is not None:
182
+ x_mask = x_mask.unsqueeze(-1).repeat(1, 1, 1, n_sqz).view(b, 1, t * n_sqz)
183
+ else:
184
+ x_mask = torch.ones(b, 1, t * n_sqz).to(device=x.device, dtype=x.dtype)
185
+ return x_unsqz * x_mask, x_mask
GPT_SoVITS/module/core_vq.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
34
+ import typing as tp
35
+
36
+ from einops import rearrange, repeat
37
+ import torch
38
+ from torch import nn
39
+ import torch.nn.functional as F
40
+ from tqdm import tqdm
41
+
42
+
43
+ def default(val: tp.Any, d: tp.Any) -> tp.Any:
44
+ return val if val is not None else d
45
+
46
+
47
+ def ema_inplace(moving_avg, new, decay: float):
48
+ moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
49
+
50
+
51
+ def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
52
+ return (x + epsilon) / (x.sum() + n_categories * epsilon)
53
+
54
+
55
+ def uniform_init(*shape: int):
56
+ t = torch.empty(shape)
57
+ nn.init.kaiming_uniform_(t)
58
+ return t
59
+
60
+
61
+ def sample_vectors(samples, num: int):
62
+ num_samples, device = samples.shape[0], samples.device
63
+
64
+ if num_samples >= num:
65
+ indices = torch.randperm(num_samples, device=device)[:num]
66
+ else:
67
+ indices = torch.randint(0, num_samples, (num,), device=device)
68
+
69
+ return samples[indices]
70
+
71
+
72
+ def kmeans(samples, num_clusters: int, num_iters: int = 10):
73
+ dim, dtype = samples.shape[-1], samples.dtype
74
+ max_kmeans_samples = 500
75
+ samples = samples[:max_kmeans_samples, :]
76
+ means = sample_vectors(samples, num_clusters)
77
+
78
+ print("kmeans start ... ")
79
+ for _ in tqdm(range(num_iters)):
80
+ diffs = rearrange(samples, "n d -> n () d") - rearrange(means, "c d -> () c d")
81
+ dists = -(diffs**2).sum(dim=-1)
82
+
83
+ buckets = dists.max(dim=-1).indices
84
+ bins = torch.bincount(buckets, minlength=num_clusters)
85
+ zero_mask = bins == 0
86
+ bins_min_clamped = bins.masked_fill(zero_mask, 1)
87
+
88
+ new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
89
+ new_means.scatter_add_(0, repeat(buckets, "n -> n d", d=dim), samples)
90
+ new_means = new_means / bins_min_clamped[..., None]
91
+
92
+ means = torch.where(zero_mask[..., None], means, new_means)
93
+
94
+ return means, bins
95
+
96
+
97
+ class EuclideanCodebook(nn.Module):
98
+ """Codebook with Euclidean distance.
99
+ Args:
100
+ dim (int): Dimension.
101
+ codebook_size (int): Codebook size.
102
+ kmeans_init (bool): Whether to use k-means to initialize the codebooks.
103
+ If set to true, run the k-means algorithm on the first training batch and use
104
+ the learned centroids as initialization.
105
+ kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
106
+ decay (float): Decay for exponential moving average over the codebooks.
107
+ epsilon (float): Epsilon value for numerical stability.
108
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
109
+ that have an exponential moving average cluster size less than the specified threshold with
110
+ randomly selected vector from the current batch.
111
+ """
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(mask[..., None], sample_vectors(samples, self.codebook_size), self.embed)
154
+ self.embed.data.copy_(modified_codebook)
155
+
156
+ def expire_codes_(self, batch_samples):
157
+ if self.threshold_ema_dead_code == 0:
158
+ return
159
+
160
+ expired_codes = self.cluster_size < self.threshold_ema_dead_code
161
+ if not torch.any(expired_codes):
162
+ return
163
+
164
+ batch_samples = rearrange(batch_samples, "... d -> (...) d")
165
+ self.replace_(batch_samples, mask=expired_codes)
166
+ # broadcast_tensors(self.buffers())
167
+
168
+ def preprocess(self, x):
169
+ x = rearrange(x, "... d -> (...) d")
170
+ return x
171
+
172
+ def quantize(self, x):
173
+ embed = self.embed.t()
174
+ dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))
175
+ embed_ind = dist.max(dim=-1).indices
176
+ return embed_ind
177
+
178
+ def postprocess_emb(self, embed_ind, shape):
179
+ return embed_ind.view(*shape[:-1])
180
+
181
+ def dequantize(self, embed_ind):
182
+ quantize = F.embedding(embed_ind, self.embed)
183
+ return quantize
184
+
185
+ def encode(self, x):
186
+ shape = x.shape
187
+ # pre-process
188
+ x = self.preprocess(x)
189
+ # quantize
190
+ embed_ind = self.quantize(x)
191
+ # post-process
192
+ embed_ind = self.postprocess_emb(embed_ind, shape)
193
+ return embed_ind
194
+
195
+ def decode(self, embed_ind):
196
+ quantize = self.dequantize(embed_ind)
197
+ return quantize
198
+
199
+ def forward(self, x):
200
+ shape, dtype = x.shape, x.dtype
201
+ x = self.preprocess(x)
202
+
203
+ self.init_embed_(x)
204
+
205
+ embed_ind = self.quantize(x)
206
+ embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)
207
+ embed_ind = self.postprocess_emb(embed_ind, shape)
208
+ quantize = self.dequantize(embed_ind)
209
+
210
+ if self.training:
211
+ # We do the expiry of code at that point as buffers are in sync
212
+ # and all the workers will take the same decision.
213
+ self.expire_codes_(x)
214
+ ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)
215
+ embed_sum = x.t() @ embed_onehot
216
+ ema_inplace(self.embed_avg, embed_sum.t(), self.decay)
217
+ cluster_size = (
218
+ laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon) * self.cluster_size.sum()
219
+ )
220
+ embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
221
+ self.embed.data.copy_(embed_normalized)
222
+
223
+ return quantize, embed_ind
224
+
225
+
226
+ class VectorQuantization(nn.Module):
227
+ """Vector quantization implementation.
228
+ Currently supports only euclidean distance.
229
+ Args:
230
+ dim (int): Dimension
231
+ codebook_size (int): Codebook size
232
+ codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
233
+ decay (float): Decay for exponential moving average over the codebooks.
234
+ epsilon (float): Epsilon value for numerical stability.
235
+ kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
236
+ kmeans_iters (int): Number of iterations used for kmeans initialization.
237
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
238
+ that have an exponential moving average cluster size less than the specified threshold with
239
+ randomly selected vector from the current batch.
240
+ commitment_weight (float): Weight for commitment loss.
241
+ """
242
+
243
+ def __init__(
244
+ self,
245
+ dim: int,
246
+ codebook_size: int,
247
+ codebook_dim: tp.Optional[int] = None,
248
+ decay: float = 0.99,
249
+ epsilon: float = 1e-5,
250
+ kmeans_init: bool = True,
251
+ kmeans_iters: int = 50,
252
+ threshold_ema_dead_code: int = 2,
253
+ commitment_weight: float = 1.0,
254
+ ):
255
+ super().__init__()
256
+ _codebook_dim: int = default(codebook_dim, dim)
257
+
258
+ requires_projection = _codebook_dim != dim
259
+ self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()
260
+ self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()
261
+
262
+ self.epsilon = epsilon
263
+ self.commitment_weight = commitment_weight
264
+
265
+ self._codebook = EuclideanCodebook(
266
+ dim=_codebook_dim,
267
+ codebook_size=codebook_size,
268
+ kmeans_init=kmeans_init,
269
+ kmeans_iters=kmeans_iters,
270
+ decay=decay,
271
+ epsilon=epsilon,
272
+ threshold_ema_dead_code=threshold_ema_dead_code,
273
+ )
274
+ self.codebook_size = codebook_size
275
+
276
+ @property
277
+ def codebook(self):
278
+ return self._codebook.embed
279
+
280
+ def encode(self, x):
281
+ x = rearrange(x, "b d n -> b n d")
282
+ x = self.project_in(x)
283
+ embed_in = self._codebook.encode(x)
284
+ return embed_in
285
+
286
+ def decode(self, embed_ind):
287
+ quantize = self._codebook.decode(embed_ind)
288
+ quantize = self.project_out(quantize)
289
+ quantize = rearrange(quantize, "b n d -> b d n")
290
+ return quantize
291
+
292
+ def forward(self, x):
293
+ device = x.device
294
+ x = rearrange(x, "b d n -> b n d")
295
+ x = self.project_in(x)
296
+
297
+ quantize, embed_ind = self._codebook(x)
298
+
299
+ if self.training:
300
+ quantize = x + (quantize - x).detach()
301
+
302
+ loss = torch.tensor([0.0], device=device, requires_grad=self.training)
303
+
304
+ if self.training:
305
+ if self.commitment_weight > 0:
306
+ commit_loss = F.mse_loss(quantize.detach(), x)
307
+ loss = loss + commit_loss * self.commitment_weight
308
+
309
+ quantize = self.project_out(quantize)
310
+ quantize = rearrange(quantize, "b n d -> b d n")
311
+ return quantize, embed_ind, loss
312
+
313
+
314
+ class ResidualVectorQuantization(nn.Module):
315
+ """Residual vector quantization implementation.
316
+ Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
317
+ """
318
+
319
+ def __init__(self, *, num_quantizers, **kwargs):
320
+ super().__init__()
321
+ self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])
322
+
323
+ def forward(self, x, n_q: tp.Optional[int] = None, layers: tp.Optional[list] = None):
324
+ quantized_out = 0.0
325
+ residual = x
326
+
327
+ all_losses = []
328
+ all_indices = []
329
+ out_quantized = []
330
+
331
+ n_q = n_q or len(self.layers)
332
+
333
+ for i, layer in enumerate(self.layers[:n_q]):
334
+ quantized, indices, loss = layer(residual)
335
+ residual = residual - quantized
336
+ quantized_out = quantized_out + quantized
337
+
338
+ all_indices.append(indices)
339
+ all_losses.append(loss)
340
+ if layers and i in layers:
341
+ out_quantized.append(quantized)
342
+
343
+ out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
344
+ return quantized_out, out_indices, out_losses, out_quantized
345
+
346
+ def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None, st: tp.Optional[int] = None) -> torch.Tensor:
347
+ residual = x
348
+ all_indices = []
349
+ n_q = n_q or len(self.layers)
350
+ st = st or 0
351
+ for layer in self.layers[st:n_q]:
352
+ indices = layer.encode(residual)
353
+ quantized = layer.decode(indices)
354
+ residual = residual - quantized
355
+ all_indices.append(indices)
356
+ out_indices = torch.stack(all_indices)
357
+ return out_indices
358
+
359
+ def decode(self, q_indices: torch.Tensor, st: int = 0) -> torch.Tensor:
360
+ quantized_out = torch.tensor(0.0, device=q_indices.device)
361
+ for i, indices in enumerate(q_indices):
362
+ layer = self.layers[st + i]
363
+ quantized = layer.decode(indices)
364
+ quantized_out = quantized_out + quantized
365
+ return quantized_out
GPT_SoVITS/module/data_utils.py ADDED
@@ -0,0 +1,1027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import traceback
4
+ import torch
5
+ import torch.utils.data
6
+ from tqdm import tqdm
7
+
8
+ from module.mel_processing import spectrogram_torch, spec_to_mel_torch
9
+ from text import cleaned_text_to_sequence
10
+ import torch.nn.functional as F
11
+ from tools.my_utils import load_audio
12
+
13
+ version = os.environ.get("version", None)
14
+
15
+
16
+ # ZeroDivisionError fixed by Tybost (https://github.com/RVC-Boss/GPT-SoVITS/issues/79)
17
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
18
+ """
19
+ 1) loads audio, speaker_id, text pairs
20
+ 2) normalizes text and converts them to sequences of integers
21
+ 3) computes spectrograms from audio files.
22
+ """
23
+
24
+ def __init__(self, hparams, val=False):
25
+ exp_dir = hparams.exp_dir
26
+ self.path2 = "%s/2-name2text.txt" % exp_dir
27
+ self.path4 = "%s/4-cnhubert" % exp_dir
28
+ self.path5 = "%s/5-wav32k" % exp_dir
29
+ assert os.path.exists(self.path2)
30
+ assert os.path.exists(self.path4)
31
+ assert os.path.exists(self.path5)
32
+ names4 = set([name[:-3] for name in list(os.listdir(self.path4))]) # 去除.pt后缀
33
+ names5 = set(os.listdir(self.path5))
34
+ self.phoneme_data = {}
35
+ with open(self.path2, "r", encoding="utf8") as f:
36
+ lines = f.read().strip("\n").split("\n")
37
+
38
+ for line in lines:
39
+ tmp = line.split("\t")
40
+ if len(tmp) != 4:
41
+ continue
42
+ self.phoneme_data[tmp[0]] = [tmp[1]]
43
+
44
+ self.audiopaths_sid_text = list(set(self.phoneme_data) & names4 & names5)
45
+ tmp = self.audiopaths_sid_text
46
+ leng = len(tmp)
47
+ min_num = 100
48
+ if leng < min_num:
49
+ self.audiopaths_sid_text = []
50
+ for _ in range(max(2, int(min_num / leng))):
51
+ self.audiopaths_sid_text += tmp
52
+ self.max_wav_value = hparams.max_wav_value
53
+ self.sampling_rate = hparams.sampling_rate
54
+ self.filter_length = hparams.filter_length
55
+ self.hop_length = hparams.hop_length
56
+ self.win_length = hparams.win_length
57
+ self.sampling_rate = hparams.sampling_rate
58
+ self.val = val
59
+
60
+ random.seed(1234)
61
+ random.shuffle(self.audiopaths_sid_text)
62
+
63
+ print("phoneme_data_len:", len(self.phoneme_data.keys()))
64
+ print("wav_data_len:", len(self.audiopaths_sid_text))
65
+
66
+ audiopaths_sid_text_new = []
67
+ lengths = []
68
+ skipped_phone = 0
69
+ skipped_dur = 0
70
+ for audiopath in tqdm(self.audiopaths_sid_text):
71
+ try:
72
+ phoneme = self.phoneme_data[audiopath][0]
73
+ phoneme = phoneme.split(" ")
74
+ phoneme_ids = cleaned_text_to_sequence(phoneme, version)
75
+ except Exception:
76
+ print(f"{audiopath} not in self.phoneme_data !")
77
+ skipped_phone += 1
78
+ continue
79
+
80
+ size = os.path.getsize("%s/%s" % (self.path5, audiopath))
81
+ duration = size / self.sampling_rate / 2
82
+
83
+ if duration == 0:
84
+ print(f"Zero duration for {audiopath}, skipping...")
85
+ skipped_dur += 1
86
+ continue
87
+
88
+ if 54 > duration > 0.6 or self.val:
89
+ audiopaths_sid_text_new.append([audiopath, phoneme_ids])
90
+ lengths.append(size // (2 * self.hop_length))
91
+ else:
92
+ skipped_dur += 1
93
+ continue
94
+
95
+ print("skipped_phone: ", skipped_phone, ", skipped_dur: ", skipped_dur)
96
+ print("total left: ", len(audiopaths_sid_text_new))
97
+ assert len(audiopaths_sid_text_new) > 1 # 至少能凑够batch size,这里todo
98
+ self.audiopaths_sid_text = audiopaths_sid_text_new
99
+ self.lengths = lengths
100
+
101
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
102
+ audiopath, phoneme_ids = audiopath_sid_text
103
+ text = torch.FloatTensor(phoneme_ids)
104
+ try:
105
+ spec, wav = self.get_audio("%s/%s" % (self.path5, audiopath))
106
+ with torch.no_grad():
107
+ ssl = torch.load("%s/%s.pt" % (self.path4, audiopath), map_location="cpu")
108
+ if ssl.shape[-1] != spec.shape[-1]:
109
+ typee = ssl.dtype
110
+ ssl = F.pad(ssl.float(), (0, 1), mode="replicate").to(typee)
111
+ ssl.requires_grad = False
112
+ except:
113
+ traceback.print_exc()
114
+ spec = torch.zeros(1025, 100)
115
+ wav = torch.zeros(1, 100 * self.hop_length)
116
+ ssl = torch.zeros(1, 768, 100)
117
+ text = text[-1:]
118
+ print("load audio or ssl error!!!!!!", audiopath)
119
+ return (ssl, spec, wav, text)
120
+
121
+ def get_audio(self, filename):
122
+ audio_array = load_audio(filename, self.sampling_rate) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768
123
+ audio = torch.FloatTensor(audio_array) # /32768
124
+ audio_norm = audio
125
+ audio_norm = audio_norm.unsqueeze(0)
126
+ spec = spectrogram_torch(
127
+ audio_norm, self.filter_length, self.sampling_rate, self.hop_length, self.win_length, center=False
128
+ )
129
+ spec = torch.squeeze(spec, 0)
130
+ return spec, audio_norm
131
+
132
+ def get_sid(self, sid):
133
+ sid = torch.LongTensor([int(sid)])
134
+ return sid
135
+
136
+ def __getitem__(self, index):
137
+ # with torch.no_grad():
138
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
139
+
140
+ def __len__(self):
141
+ return len(self.audiopaths_sid_text)
142
+
143
+ def random_slice(self, ssl, wav, mel):
144
+ assert abs(ssl.shape[-1] - wav.shape[-1] // self.hop_length) < 3, ("first", ssl.shape, wav.shape)
145
+
146
+ len_mel = mel.shape[1]
147
+ if self.val:
148
+ reference_mel = mel[:, : len_mel // 3]
149
+ return reference_mel, ssl, wav, mel
150
+ dir = random.randint(0, 1)
151
+ sep_point = random.randint(int(len_mel // 3), int(len_mel // 3 * 2))
152
+
153
+ if dir == 0:
154
+ reference_mel = mel[:, :sep_point]
155
+ ssl = ssl[:, :, sep_point:]
156
+ wav2 = wav[:, sep_point * self.hop_length :]
157
+ mel = mel[:, sep_point:]
158
+ else:
159
+ reference_mel = mel[:, sep_point:]
160
+ ssl = ssl[:, :, :sep_point]
161
+ wav2 = wav[:, : sep_point * self.hop_length]
162
+ mel = mel[:, :sep_point]
163
+
164
+ assert abs(ssl.shape[-1] - wav2.shape[-1] // self.hop_length) < 3, (
165
+ ssl.shape,
166
+ wav.shape,
167
+ wav2.shape,
168
+ mel.shape,
169
+ sep_point,
170
+ self.hop_length,
171
+ sep_point * self.hop_length,
172
+ dir,
173
+ )
174
+ return reference_mel, ssl, wav2, mel
175
+
176
+
177
+ class TextAudioSpeakerCollate:
178
+ """Zero-pads model inputs and targets"""
179
+
180
+ def __init__(self, return_ids=False):
181
+ self.return_ids = return_ids
182
+
183
+ def __call__(self, batch):
184
+ """Collate's training batch from normalized text, audio and speaker identities
185
+ PARAMS
186
+ ------
187
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
188
+ """
189
+ # Right zero-pad all one-hot text sequences to max input length
190
+ _, ids_sorted_decreasing = torch.sort(torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True)
191
+
192
+ max_ssl_len = max([x[0].size(2) for x in batch])
193
+ max_ssl_len = int(2 * ((max_ssl_len // 2) + 1))
194
+ max_spec_len = max([x[1].size(1) for x in batch])
195
+ max_spec_len = int(2 * ((max_spec_len // 2) + 1))
196
+ max_wav_len = max([x[2].size(1) for x in batch])
197
+ max_text_len = max([x[3].size(0) for x in batch])
198
+
199
+ ssl_lengths = torch.LongTensor(len(batch))
200
+ spec_lengths = torch.LongTensor(len(batch))
201
+ wav_lengths = torch.LongTensor(len(batch))
202
+ text_lengths = torch.LongTensor(len(batch))
203
+
204
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
205
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
206
+ ssl_padded = torch.FloatTensor(len(batch), batch[0][0].size(1), max_ssl_len)
207
+ text_padded = torch.LongTensor(len(batch), max_text_len)
208
+
209
+ spec_padded.zero_()
210
+ wav_padded.zero_()
211
+ ssl_padded.zero_()
212
+ text_padded.zero_()
213
+
214
+ for i in range(len(ids_sorted_decreasing)):
215
+ row = batch[ids_sorted_decreasing[i]]
216
+
217
+ ssl = row[0]
218
+ ssl_padded[i, :, : ssl.size(2)] = ssl[0, :, :]
219
+ ssl_lengths[i] = ssl.size(2)
220
+
221
+ spec = row[1]
222
+ spec_padded[i, :, : spec.size(1)] = spec
223
+ spec_lengths[i] = spec.size(1)
224
+
225
+ wav = row[2]
226
+ wav_padded[i, :, : wav.size(1)] = wav
227
+ wav_lengths[i] = wav.size(1)
228
+
229
+ text = row[3]
230
+ text_padded[i, : text.size(0)] = text
231
+ text_lengths[i] = text.size(0)
232
+
233
+ return ssl_padded, ssl_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, text_padded, text_lengths
234
+
235
+
236
+ class TextAudioSpeakerLoaderV3(torch.utils.data.Dataset):
237
+ """
238
+ 1) loads audio, speaker_id, text pairs
239
+ 2) normalizes text and converts them to sequences of integers
240
+ 3) computes spectrograms from audio files.
241
+ """
242
+
243
+ def __init__(self, hparams, val=False):
244
+ exp_dir = hparams.exp_dir
245
+ self.path2 = "%s/2-name2text.txt" % exp_dir
246
+ self.path4 = "%s/4-cnhubert" % exp_dir
247
+ self.path5 = "%s/5-wav32k" % exp_dir
248
+ assert os.path.exists(self.path2)
249
+ assert os.path.exists(self.path4)
250
+ assert os.path.exists(self.path5)
251
+ names4 = set([name[:-3] for name in list(os.listdir(self.path4))]) # 去除.pt后缀
252
+ names5 = set(os.listdir(self.path5))
253
+ self.phoneme_data = {}
254
+ with open(self.path2, "r", encoding="utf8") as f:
255
+ lines = f.read().strip("\n").split("\n")
256
+
257
+ for line in lines:
258
+ tmp = line.split("\t")
259
+ if len(tmp) != 4:
260
+ continue
261
+ self.phoneme_data[tmp[0]] = [tmp[1]]
262
+
263
+ self.audiopaths_sid_text = list(set(self.phoneme_data) & names4 & names5)
264
+ tmp = self.audiopaths_sid_text
265
+ leng = len(tmp)
266
+ min_num = 100
267
+ if leng < min_num:
268
+ self.audiopaths_sid_text = []
269
+ for _ in range(max(2, int(min_num / leng))):
270
+ self.audiopaths_sid_text += tmp
271
+ self.max_wav_value = hparams.max_wav_value
272
+ self.sampling_rate = hparams.sampling_rate
273
+ self.filter_length = hparams.filter_length
274
+ self.hop_length = hparams.hop_length
275
+ self.win_length = hparams.win_length
276
+ self.sampling_rate = hparams.sampling_rate
277
+ self.val = val
278
+
279
+ random.seed(1234)
280
+ random.shuffle(self.audiopaths_sid_text)
281
+
282
+ print("phoneme_data_len:", len(self.phoneme_data.keys()))
283
+ print("wav_data_len:", len(self.audiopaths_sid_text))
284
+
285
+ audiopaths_sid_text_new = []
286
+ lengths = []
287
+ skipped_phone = 0
288
+ skipped_dur = 0
289
+ for audiopath in tqdm(self.audiopaths_sid_text):
290
+ try:
291
+ phoneme = self.phoneme_data[audiopath][0]
292
+ phoneme = phoneme.split(" ")
293
+ phoneme_ids = cleaned_text_to_sequence(phoneme, version)
294
+ except Exception:
295
+ print(f"{audiopath} not in self.phoneme_data !")
296
+ skipped_phone += 1
297
+ continue
298
+
299
+ size = os.path.getsize("%s/%s" % (self.path5, audiopath))
300
+ duration = size / self.sampling_rate / 2
301
+
302
+ if duration == 0:
303
+ print(f"Zero duration for {audiopath}, skipping...")
304
+ skipped_dur += 1
305
+ continue
306
+
307
+ if 54 > duration > 0.6 or self.val:
308
+ audiopaths_sid_text_new.append([audiopath, phoneme_ids])
309
+ lengths.append(size // (2 * self.hop_length))
310
+ else:
311
+ skipped_dur += 1
312
+ continue
313
+
314
+ print("skipped_phone: ", skipped_phone, ", skipped_dur: ", skipped_dur)
315
+ print("total left: ", len(audiopaths_sid_text_new))
316
+ assert len(audiopaths_sid_text_new) > 1 # 至少能凑够batch size,这里todo
317
+ self.audiopaths_sid_text = audiopaths_sid_text_new
318
+ self.lengths = lengths
319
+ self.spec_min = -12
320
+ self.spec_max = 2
321
+
322
+ self.filter_length_mel = self.win_length_mel = 1024
323
+ self.hop_length_mel = 256
324
+ self.n_mel_channels = 100
325
+ self.sampling_rate_mel = 24000
326
+ self.mel_fmin = 0
327
+ self.mel_fmax = None
328
+
329
+ def norm_spec(self, x):
330
+ return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
331
+
332
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
333
+ audiopath, phoneme_ids = audiopath_sid_text
334
+ text = torch.FloatTensor(phoneme_ids)
335
+ try:
336
+ spec, mel = self.get_audio("%s/%s" % (self.path5, audiopath))
337
+ with torch.no_grad():
338
+ ssl = torch.load("%s/%s.pt" % (self.path4, audiopath), map_location="cpu")
339
+ if ssl.shape[-1] != spec.shape[-1]:
340
+ typee = ssl.dtype
341
+ ssl = F.pad(ssl.float(), (0, 1), mode="replicate").to(typee)
342
+ ssl.requires_grad = False
343
+ except:
344
+ traceback.print_exc()
345
+ mel = torch.zeros(100, 180)
346
+ # wav = torch.zeros(1, 96 * self.hop_length)
347
+ spec = torch.zeros(1025, 96)
348
+ ssl = torch.zeros(1, 768, 96)
349
+ text = text[-1:]
350
+ print("load audio or ssl error!!!!!!", audiopath)
351
+ return (ssl, spec, mel, text)
352
+
353
+ def get_audio(self, filename):
354
+ audio_array = load_audio(filename, self.sampling_rate) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768
355
+ audio = torch.FloatTensor(audio_array) # /32768
356
+ audio_norm = audio
357
+ audio_norm = audio_norm.unsqueeze(0)
358
+ audio_array24 = load_audio(
359
+ filename, 24000
360
+ ) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768######这里可以用GPU重采样加速
361
+ audio24 = torch.FloatTensor(audio_array24) # /32768
362
+ audio_norm24 = audio24
363
+ audio_norm24 = audio_norm24.unsqueeze(0)
364
+
365
+ spec = spectrogram_torch(
366
+ audio_norm, self.filter_length, self.sampling_rate, self.hop_length, self.win_length, center=False
367
+ )
368
+ spec = torch.squeeze(spec, 0)
369
+
370
+ spec1 = spectrogram_torch(
371
+ audio_norm24,
372
+ self.filter_length_mel,
373
+ self.sampling_rate_mel,
374
+ self.hop_length_mel,
375
+ self.win_length_mel,
376
+ center=False,
377
+ )
378
+ mel = spec_to_mel_torch(
379
+ spec1, self.filter_length_mel, self.n_mel_channels, self.sampling_rate_mel, self.mel_fmin, self.mel_fmax
380
+ )
381
+ mel = torch.squeeze(mel, 0)
382
+ mel = self.norm_spec(mel)
383
+ # print(1111111,spec.shape,mel.shape)
384
+ return spec, mel
385
+
386
+ def get_sid(self, sid):
387
+ sid = torch.LongTensor([int(sid)])
388
+ return sid
389
+
390
+ def __getitem__(self, index):
391
+ # with torch.no_grad():
392
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
393
+
394
+ def __len__(self):
395
+ return len(self.audiopaths_sid_text)
396
+
397
+
398
+ class TextAudioSpeakerCollateV3:
399
+ """Zero-pads model inputs and targets"""
400
+
401
+ def __init__(self, return_ids=False):
402
+ self.return_ids = return_ids
403
+
404
+ def __call__(self, batch):
405
+ """Collate's training batch from normalized text, audio and speaker identities
406
+ PARAMS
407
+ ------
408
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
409
+ """
410
+ # ssl, spec, wav,mel, text
411
+ # Right zero-pad all one-hot text sequences to max input length
412
+ _, ids_sorted_decreasing = torch.sort(torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True)
413
+ # (ssl, spec,mel, text)
414
+ max_ssl_len = max([x[0].size(2) for x in batch])
415
+
416
+ max_ssl_len1 = int(8 * ((max_ssl_len // 8) + 1))
417
+ max_ssl_len = int(2 * ((max_ssl_len // 2) + 1))
418
+
419
+ # max_ssl_len = int(8 * ((max_ssl_len // 8) + 1))
420
+ # max_ssl_len1=max_ssl_len
421
+
422
+ max_spec_len = max([x[1].size(1) for x in batch])
423
+ max_spec_len = int(2 * ((max_spec_len // 2) + 1))
424
+ # max_wav_len = max([x[2].size(1) for x in batch])
425
+
426
+ max_text_len = max([x[3].size(0) for x in batch])
427
+ max_mel_len = int(max_ssl_len1 * 1.25 * 1.5) ###24000/256,32000/640=16000/320
428
+
429
+ ssl_lengths = torch.LongTensor(len(batch))
430
+ spec_lengths = torch.LongTensor(len(batch))
431
+ text_lengths = torch.LongTensor(len(batch))
432
+ # wav_lengths = torch.LongTensor(len(batch))
433
+ mel_lengths = torch.LongTensor(len(batch))
434
+
435
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
436
+ mel_padded = torch.FloatTensor(len(batch), batch[0][2].size(0), max_mel_len)
437
+ ssl_padded = torch.FloatTensor(len(batch), batch[0][0].size(1), max_ssl_len)
438
+ text_padded = torch.LongTensor(len(batch), max_text_len)
439
+ # wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
440
+
441
+ spec_padded.zero_()
442
+ mel_padded.zero_()
443
+ ssl_padded.zero_()
444
+ text_padded.zero_()
445
+ # wav_padded.zero_()
446
+
447
+ for i in range(len(ids_sorted_decreasing)):
448
+ row = batch[ids_sorted_decreasing[i]]
449
+ # ssl, spec, wav,mel, text
450
+ ssl = row[0]
451
+ ssl_padded[i, :, : ssl.size(2)] = ssl[0, :, :]
452
+ ssl_lengths[i] = ssl.size(2)
453
+
454
+ spec = row[1]
455
+ spec_padded[i, :, : spec.size(1)] = spec
456
+ spec_lengths[i] = spec.size(1)
457
+
458
+ # wav = row[2]
459
+ # wav_padded[i, :, :wav.size(1)] = wav
460
+ # wav_lengths[i] = wav.size(1)
461
+
462
+ mel = row[2]
463
+ mel_padded[i, :, : mel.size(1)] = mel
464
+ mel_lengths[i] = mel.size(1)
465
+
466
+ text = row[3]
467
+ text_padded[i, : text.size(0)] = text
468
+ text_lengths[i] = text.size(0)
469
+
470
+ # return ssl_padded, spec_padded,mel_padded, ssl_lengths, spec_lengths, text_padded, text_lengths, wav_padded, wav_lengths,mel_lengths
471
+ return ssl_padded, spec_padded, mel_padded, ssl_lengths, spec_lengths, text_padded, text_lengths, mel_lengths
472
+
473
+ class TextAudioSpeakerLoaderV4(torch.utils.data.Dataset):
474
+ """
475
+ 1) loads audio, speaker_id, text pairs
476
+ 2) normalizes text and converts them to sequences of integers
477
+ 3) computes spectrograms from audio files.
478
+ """
479
+
480
+ def __init__(self, hparams, val=False):
481
+ exp_dir = hparams.exp_dir
482
+ self.path2 = "%s/2-name2text.txt" % exp_dir
483
+ self.path4 = "%s/4-cnhubert" % exp_dir
484
+ self.path5 = "%s/5-wav32k" % exp_dir
485
+ assert os.path.exists(self.path2)
486
+ assert os.path.exists(self.path4)
487
+ assert os.path.exists(self.path5)
488
+ names4 = set([name[:-3] for name in list(os.listdir(self.path4))]) # 去除.pt后缀
489
+ names5 = set(os.listdir(self.path5))
490
+ self.phoneme_data = {}
491
+ with open(self.path2, "r", encoding="utf8") as f:
492
+ lines = f.read().strip("\n").split("\n")
493
+
494
+ for line in lines:
495
+ tmp = line.split("\t")
496
+ if len(tmp) != 4:
497
+ continue
498
+ self.phoneme_data[tmp[0]] = [tmp[1]]
499
+
500
+ self.audiopaths_sid_text = list(set(self.phoneme_data) & names4 & names5)
501
+ tmp = self.audiopaths_sid_text
502
+ leng = len(tmp)
503
+ min_num = 100
504
+ if leng < min_num:
505
+ self.audiopaths_sid_text = []
506
+ for _ in range(max(2, int(min_num / leng))):
507
+ self.audiopaths_sid_text += tmp
508
+ self.max_wav_value = hparams.max_wav_value
509
+ self.sampling_rate = hparams.sampling_rate
510
+ self.filter_length = hparams.filter_length
511
+ self.hop_length = hparams.hop_length
512
+ self.win_length = hparams.win_length
513
+ self.sampling_rate = hparams.sampling_rate
514
+ self.val = val
515
+
516
+ random.seed(1234)
517
+ random.shuffle(self.audiopaths_sid_text)
518
+
519
+ print("phoneme_data_len:", len(self.phoneme_data.keys()))
520
+ print("wav_data_len:", len(self.audiopaths_sid_text))
521
+
522
+ audiopaths_sid_text_new = []
523
+ lengths = []
524
+ skipped_phone = 0
525
+ skipped_dur = 0
526
+ for audiopath in tqdm(self.audiopaths_sid_text):
527
+ try:
528
+ phoneme = self.phoneme_data[audiopath][0]
529
+ phoneme = phoneme.split(" ")
530
+ phoneme_ids = cleaned_text_to_sequence(phoneme, version)
531
+ except Exception:
532
+ print(f"{audiopath} not in self.phoneme_data !")
533
+ skipped_phone += 1
534
+ continue
535
+
536
+ size = os.path.getsize("%s/%s" % (self.path5, audiopath))
537
+ duration = size / self.sampling_rate / 2
538
+
539
+ if duration == 0:
540
+ print(f"Zero duration for {audiopath}, skipping...")
541
+ skipped_dur += 1
542
+ continue
543
+
544
+ if 54 > duration > 0.6 or self.val:
545
+ audiopaths_sid_text_new.append([audiopath, phoneme_ids])
546
+ lengths.append(size // (2 * self.hop_length))
547
+ else:
548
+ skipped_dur += 1
549
+ continue
550
+
551
+ print("skipped_phone: ", skipped_phone, ", skipped_dur: ", skipped_dur)
552
+ print("total left: ", len(audiopaths_sid_text_new))
553
+ assert len(audiopaths_sid_text_new) > 1 # 至少能凑够batch size,这里todo
554
+ self.audiopaths_sid_text = audiopaths_sid_text_new
555
+ self.lengths = lengths
556
+ self.spec_min = -12
557
+ self.spec_max = 2
558
+
559
+ self.filter_length_mel = self.win_length_mel = 1280
560
+ self.hop_length_mel = 320
561
+ self.n_mel_channels = 100
562
+ self.sampling_rate_mel = 32000
563
+ self.mel_fmin = 0
564
+ self.mel_fmax = None
565
+
566
+ def norm_spec(self, x):
567
+ return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
568
+
569
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
570
+ audiopath, phoneme_ids = audiopath_sid_text
571
+ text = torch.FloatTensor(phoneme_ids)
572
+ try:
573
+ spec, mel = self.get_audio("%s/%s" % (self.path5, audiopath))
574
+ with torch.no_grad():
575
+ ssl = torch.load("%s/%s.pt" % (self.path4, audiopath), map_location="cpu")
576
+ if ssl.shape[-1] != spec.shape[-1]:
577
+ typee = ssl.dtype
578
+ ssl = F.pad(ssl.float(), (0, 1), mode="replicate").to(typee)
579
+ ssl.requires_grad = False
580
+ except:
581
+ traceback.print_exc()
582
+ mel = torch.zeros(100, 192)
583
+ # wav = torch.zeros(1, 96 * self.hop_length)
584
+ spec = torch.zeros(1025, 96)
585
+ ssl = torch.zeros(1, 768, 96)
586
+ text = text[-1:]
587
+ print("load audio or ssl error!!!!!!", audiopath)
588
+ return (ssl, spec, mel, text)
589
+
590
+ def get_audio(self, filename):
591
+ audio_array = load_audio(filename, self.sampling_rate) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768
592
+ audio = torch.FloatTensor(audio_array) # /32768
593
+ audio_norm = audio
594
+ audio_norm = audio_norm.unsqueeze(0)
595
+ spec = spectrogram_torch(
596
+ audio_norm, self.filter_length, self.sampling_rate, self.hop_length, self.win_length, center=False
597
+ )
598
+ spec = torch.squeeze(spec, 0)
599
+ spec1 = spectrogram_torch(audio_norm, 1280,32000, 320, 1280,center=False)
600
+ mel = spec_to_mel_torch(spec1, 1280, 100, 32000, 0, None)
601
+ mel = self.norm_spec(torch.squeeze(mel, 0))
602
+ return spec, mel
603
+
604
+ def get_sid(self, sid):
605
+ sid = torch.LongTensor([int(sid)])
606
+ return sid
607
+
608
+ def __getitem__(self, index):
609
+ # with torch.no_grad():
610
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
611
+
612
+ def __len__(self):
613
+ return len(self.audiopaths_sid_text)
614
+
615
+
616
+ class TextAudioSpeakerCollateV4:
617
+ """Zero-pads model inputs and targets"""
618
+
619
+ def __init__(self, return_ids=False):
620
+ self.return_ids = return_ids
621
+
622
+ def __call__(self, batch):
623
+ """Collate's training batch from normalized text, audio and speaker identities
624
+ PARAMS
625
+ ------
626
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
627
+ """
628
+ # ssl, spec, wav,mel, text
629
+ # Right zero-pad all one-hot text sequences to max input length
630
+ _, ids_sorted_decreasing = torch.sort(torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True)
631
+ # (ssl, spec,mel, text)
632
+ max_ssl_len = max([x[0].size(2) for x in batch])
633
+ max_ssl_len = int(2 * ((max_ssl_len // 2) + 1))
634
+ max_spec_len = max([x[1].size(1) for x in batch])
635
+ max_spec_len = int(2 * ((max_spec_len // 2) + 1))
636
+ # max_wav_len = max([x[2].size(1) for x in batch])
637
+ max_text_len = max([x[3].size(0) for x in batch])
638
+
639
+ ssl_lengths = torch.LongTensor(len(batch))
640
+ spec_lengths = torch.LongTensor(len(batch))
641
+ text_lengths = torch.LongTensor(len(batch))
642
+ # wav_lengths = torch.LongTensor(len(batch))
643
+ mel_lengths = torch.LongTensor(len(batch))
644
+
645
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
646
+ mel_padded = torch.FloatTensor(len(batch), batch[0][2].size(0), max_spec_len*2)
647
+ ssl_padded = torch.FloatTensor(len(batch), batch[0][0].size(1), max_ssl_len)
648
+ text_padded = torch.LongTensor(len(batch), max_text_len)
649
+ # wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
650
+
651
+ spec_padded.zero_()
652
+ mel_padded.zero_()
653
+ ssl_padded.zero_()
654
+ text_padded.zero_()
655
+ # wav_padded.zero_()
656
+
657
+ for i in range(len(ids_sorted_decreasing)):
658
+ row = batch[ids_sorted_decreasing[i]]
659
+ # ssl, spec, wav,mel, text
660
+ ssl = row[0]
661
+ ssl_padded[i, :, : ssl.size(2)] = ssl[0, :, :]
662
+ ssl_lengths[i] = ssl.size(2)
663
+
664
+ spec = row[1]
665
+ spec_padded[i, :, : spec.size(1)] = spec
666
+ spec_lengths[i] = spec.size(1)
667
+
668
+ # wav = row[2]
669
+ # wav_padded[i, :, :wav.size(1)] = wav
670
+ # wav_lengths[i] = wav.size(1)
671
+
672
+ mel = row[2]
673
+ mel_padded[i, :, : mel.size(1)] = mel
674
+ mel_lengths[i] = mel.size(1)
675
+
676
+ text = row[3]
677
+ text_padded[i, : text.size(0)] = text
678
+ text_lengths[i] = text.size(0)
679
+
680
+ # return ssl_padded, spec_padded,mel_padded, ssl_lengths, spec_lengths, text_padded, text_lengths, wav_padded, wav_lengths,mel_lengths
681
+ return ssl_padded, spec_padded, mel_padded, ssl_lengths, spec_lengths, text_padded, text_lengths, mel_lengths
682
+
683
+
684
+ class TextAudioSpeakerLoaderV3b(torch.utils.data.Dataset):
685
+ """
686
+ 1) loads audio, speaker_id, text pairs
687
+ 2) normalizes text and converts them to sequences of integers
688
+ 3) computes spectrograms from audio files.
689
+ """
690
+
691
+ def __init__(self, hparams, val=False):
692
+ exp_dir = hparams.exp_dir
693
+ self.path2 = "%s/2-name2text.txt" % exp_dir
694
+ self.path4 = "%s/4-cnhubert" % exp_dir
695
+ self.path5 = "%s/5-wav32k" % exp_dir
696
+ assert os.path.exists(self.path2)
697
+ assert os.path.exists(self.path4)
698
+ assert os.path.exists(self.path5)
699
+ names4 = set([name[:-3] for name in list(os.listdir(self.path4))]) # 去除.pt后缀
700
+ names5 = set(os.listdir(self.path5))
701
+ self.phoneme_data = {}
702
+ with open(self.path2, "r", encoding="utf8") as f:
703
+ lines = f.read().strip("\n").split("\n")
704
+
705
+ for line in lines:
706
+ tmp = line.split("\t")
707
+ if len(tmp) != 4:
708
+ continue
709
+ self.phoneme_data[tmp[0]] = [tmp[1]]
710
+
711
+ self.audiopaths_sid_text = list(set(self.phoneme_data) & names4 & names5)
712
+ tmp = self.audiopaths_sid_text
713
+ leng = len(tmp)
714
+ min_num = 100
715
+ if leng < min_num:
716
+ self.audiopaths_sid_text = []
717
+ for _ in range(max(2, int(min_num / leng))):
718
+ self.audiopaths_sid_text += tmp
719
+ self.max_wav_value = hparams.max_wav_value
720
+ self.sampling_rate = hparams.sampling_rate
721
+ self.filter_length = hparams.filter_length
722
+ self.hop_length = hparams.hop_length
723
+ self.win_length = hparams.win_length
724
+ self.sampling_rate = hparams.sampling_rate
725
+ self.val = val
726
+
727
+ random.seed(1234)
728
+ random.shuffle(self.audiopaths_sid_text)
729
+
730
+ print("phoneme_data_len:", len(self.phoneme_data.keys()))
731
+ print("wav_data_len:", len(self.audiopaths_sid_text))
732
+
733
+ audiopaths_sid_text_new = []
734
+ lengths = []
735
+ skipped_phone = 0
736
+ skipped_dur = 0
737
+ for audiopath in tqdm(self.audiopaths_sid_text):
738
+ try:
739
+ phoneme = self.phoneme_data[audiopath][0]
740
+ phoneme = phoneme.split(" ")
741
+ phoneme_ids = cleaned_text_to_sequence(phoneme, version)
742
+ except Exception:
743
+ print(f"{audiopath} not in self.phoneme_data !")
744
+ skipped_phone += 1
745
+ continue
746
+
747
+ size = os.path.getsize("%s/%s" % (self.path5, audiopath))
748
+ duration = size / self.sampling_rate / 2
749
+
750
+ if duration == 0:
751
+ print(f"Zero duration for {audiopath}, skipping...")
752
+ skipped_dur += 1
753
+ continue
754
+
755
+ if 54 > duration > 0.6 or self.val:
756
+ audiopaths_sid_text_new.append([audiopath, phoneme_ids])
757
+ lengths.append(size // (2 * self.hop_length))
758
+ else:
759
+ skipped_dur += 1
760
+ continue
761
+
762
+ print("skipped_phone: ", skipped_phone, ", skipped_dur: ", skipped_dur)
763
+ print("total left: ", len(audiopaths_sid_text_new))
764
+ assert len(audiopaths_sid_text_new) > 1 # 至少能凑够batch size,这里todo
765
+ self.audiopaths_sid_text = audiopaths_sid_text_new
766
+ self.lengths = lengths
767
+ self.spec_min = -12
768
+ self.spec_max = 2
769
+
770
+ self.filter_length_mel = self.win_length_mel = 1024
771
+ self.hop_length_mel = 256
772
+ self.n_mel_channels = 100
773
+ self.sampling_rate_mel = 24000
774
+ self.mel_fmin = 0
775
+ self.mel_fmax = None
776
+
777
+ def norm_spec(self, x):
778
+ return (x - self.spec_min) / (self.spec_max - self.spec_min) * 2 - 1
779
+
780
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
781
+ audiopath, phoneme_ids = audiopath_sid_text
782
+ text = torch.FloatTensor(phoneme_ids)
783
+ try:
784
+ spec, mel, wav = self.get_audio("%s/%s" % (self.path5, audiopath))
785
+ with torch.no_grad():
786
+ ssl = torch.load("%s/%s.pt" % (self.path4, audiopath), map_location="cpu")
787
+ if ssl.shape[-1] != spec.shape[-1]:
788
+ typee = ssl.dtype
789
+ ssl = F.pad(ssl.float(), (0, 1), mode="replicate").to(typee)
790
+ ssl.requires_grad = False
791
+ except:
792
+ traceback.print_exc()
793
+ mel = torch.zeros(100, 180)
794
+ wav = torch.zeros(1, 96 * self.hop_length)
795
+ spec = torch.zeros(1025, 96)
796
+ ssl = torch.zeros(1, 768, 96)
797
+ text = text[-1:]
798
+ print("load audio or ssl error!!!!!!", audiopath)
799
+ return (ssl, spec, wav, mel, text)
800
+
801
+ def get_audio(self, filename):
802
+ audio_array = load_audio(filename, self.sampling_rate) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768
803
+ audio = torch.FloatTensor(audio_array) # /32768
804
+ audio_norm = audio
805
+ audio_norm = audio_norm.unsqueeze(0)
806
+ audio_array24 = load_audio(
807
+ filename, 24000
808
+ ) # load_audio的方法是已经归一化到-1~1之间的,不用再/32768######这里可以用GPU重采样加速
809
+ audio24 = torch.FloatTensor(audio_array24) # /32768
810
+ audio_norm24 = audio24
811
+ audio_norm24 = audio_norm24.unsqueeze(0)
812
+
813
+ spec = spectrogram_torch(
814
+ audio_norm, self.filter_length, self.sampling_rate, self.hop_length, self.win_length, center=False
815
+ )
816
+ spec = torch.squeeze(spec, 0)
817
+
818
+ spec1 = spectrogram_torch(
819
+ audio_norm24,
820
+ self.filter_length_mel,
821
+ self.sampling_rate_mel,
822
+ self.hop_length_mel,
823
+ self.win_length_mel,
824
+ center=False,
825
+ )
826
+ mel = spec_to_mel_torch(
827
+ spec1, self.filter_length_mel, self.n_mel_channels, self.sampling_rate_mel, self.mel_fmin, self.mel_fmax
828
+ )
829
+ mel = torch.squeeze(mel, 0)
830
+ mel = self.norm_spec(mel)
831
+ # print(1111111,spec.shape,mel.shape)
832
+ return spec, mel, audio_norm
833
+
834
+ def get_sid(self, sid):
835
+ sid = torch.LongTensor([int(sid)])
836
+ return sid
837
+
838
+ def __getitem__(self, index):
839
+ # with torch.no_grad():
840
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
841
+
842
+ def __len__(self):
843
+ return len(self.audiopaths_sid_text)
844
+
845
+
846
+ class TextAudioSpeakerCollateV3b:
847
+ """Zero-pads model inputs and targets"""
848
+
849
+ def __init__(self, return_ids=False):
850
+ self.return_ids = return_ids
851
+
852
+ def __call__(self, batch):
853
+ """Collate's training batch from normalized text, audio and speaker identities
854
+ PARAMS
855
+ ------
856
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
857
+ """
858
+ # ssl, spec, wav,mel, text
859
+ # Right zero-pad all one-hot text sequences to max input length
860
+ _, ids_sorted_decreasing = torch.sort(torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True)
861
+ # (ssl, spec,mel, text)
862
+ max_ssl_len = max([x[0].size(2) for x in batch])
863
+
864
+ max_ssl_len1 = int(8 * ((max_ssl_len // 8) + 1))
865
+ max_ssl_len = int(2 * ((max_ssl_len // 2) + 1))
866
+
867
+ # max_ssl_len = int(8 * ((max_ssl_len // 8) + 1))
868
+ # max_ssl_len1=max_ssl_len
869
+
870
+ max_spec_len = max([x[1].size(1) for x in batch])
871
+ max_spec_len = int(2 * ((max_spec_len // 2) + 1))
872
+ max_wav_len = max([x[2].size(1) for x in batch])
873
+ max_text_len = max([x[4].size(0) for x in batch])
874
+ max_mel_len = int(max_ssl_len1 * 1.25 * 1.5) ###24000/256,32000/640=16000/320
875
+
876
+ ssl_lengths = torch.LongTensor(len(batch))
877
+ spec_lengths = torch.LongTensor(len(batch))
878
+ text_lengths = torch.LongTensor(len(batch))
879
+ wav_lengths = torch.LongTensor(len(batch))
880
+ mel_lengths = torch.LongTensor(len(batch))
881
+
882
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
883
+ mel_padded = torch.FloatTensor(len(batch), batch[0][3].size(0), max_mel_len)
884
+ ssl_padded = torch.FloatTensor(len(batch), batch[0][0].size(1), max_ssl_len)
885
+ text_padded = torch.LongTensor(len(batch), max_text_len)
886
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
887
+
888
+ spec_padded.zero_()
889
+ mel_padded.zero_()
890
+ ssl_padded.zero_()
891
+ text_padded.zero_()
892
+ wav_padded.zero_()
893
+
894
+ for i in range(len(ids_sorted_decreasing)):
895
+ row = batch[ids_sorted_decreasing[i]]
896
+ # ssl, spec, wav,mel, text
897
+ ssl = row[0]
898
+ ssl_padded[i, :, : ssl.size(2)] = ssl[0, :, :]
899
+ ssl_lengths[i] = ssl.size(2)
900
+
901
+ spec = row[1]
902
+ spec_padded[i, :, : spec.size(1)] = spec
903
+ spec_lengths[i] = spec.size(1)
904
+
905
+ wav = row[2]
906
+ wav_padded[i, :, : wav.size(1)] = wav
907
+ wav_lengths[i] = wav.size(1)
908
+
909
+ mel = row[3]
910
+ mel_padded[i, :, : mel.size(1)] = mel
911
+ mel_lengths[i] = mel.size(1)
912
+
913
+ text = row[4]
914
+ text_padded[i, : text.size(0)] = text
915
+ text_lengths[i] = text.size(0)
916
+
917
+ return (
918
+ ssl_padded,
919
+ spec_padded,
920
+ mel_padded,
921
+ ssl_lengths,
922
+ spec_lengths,
923
+ text_padded,
924
+ text_lengths,
925
+ wav_padded,
926
+ wav_lengths,
927
+ mel_lengths,
928
+ )
929
+ # return ssl_padded, spec_padded,mel_padded, ssl_lengths, spec_lengths, text_padded, text_lengths,mel_lengths
930
+
931
+
932
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
933
+ """
934
+ Maintain similar input lengths in a batch.
935
+ Length groups are specified by boundaries.
936
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
937
+
938
+ It removes samples which are not included in the boundaries.
939
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
940
+ """
941
+
942
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
943
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
944
+ self.lengths = dataset.lengths
945
+ self.batch_size = batch_size
946
+ self.boundaries = boundaries
947
+
948
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
949
+ self.total_size = sum(self.num_samples_per_bucket)
950
+ self.num_samples = self.total_size // self.num_replicas
951
+
952
+ def _create_buckets(self):
953
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
954
+ for i in range(len(self.lengths)):
955
+ length = self.lengths[i]
956
+ idx_bucket = self._bisect(length)
957
+ if idx_bucket != -1:
958
+ buckets[idx_bucket].append(i)
959
+
960
+ i = len(buckets) - 1
961
+ while i >= 0:
962
+ if len(buckets[i]) == 0:
963
+ buckets.pop(i)
964
+ self.boundaries.pop(i + 1)
965
+ i -= 1
966
+
967
+ num_samples_per_bucket = []
968
+ for i in range(len(buckets)):
969
+ len_bucket = len(buckets[i])
970
+ total_batch_size = self.num_replicas * self.batch_size
971
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
972
+ num_samples_per_bucket.append(len_bucket + rem)
973
+ return buckets, num_samples_per_bucket
974
+
975
+ def __iter__(self):
976
+ g = torch.Generator()
977
+ g.manual_seed(self.epoch)
978
+
979
+ indices = []
980
+ if self.shuffle:
981
+ for bucket in self.buckets:
982
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
983
+ else:
984
+ for bucket in self.buckets:
985
+ indices.append(list(range(len(bucket))))
986
+
987
+ batches = []
988
+ for i in range(len(self.buckets)):
989
+ bucket = self.buckets[i]
990
+ len_bucket = len(bucket)
991
+ ids_bucket = indices[i]
992
+ num_samples_bucket = self.num_samples_per_bucket[i]
993
+
994
+ rem = num_samples_bucket - len_bucket
995
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[: (rem % len_bucket)]
996
+
997
+ ids_bucket = ids_bucket[self.rank :: self.num_replicas]
998
+
999
+ for j in range(len(ids_bucket) // self.batch_size):
1000
+ batch = [bucket[idx] for idx in ids_bucket[j * self.batch_size : (j + 1) * self.batch_size]]
1001
+ batches.append(batch)
1002
+
1003
+ if self.shuffle:
1004
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
1005
+ batches = [batches[i] for i in batch_ids]
1006
+ self.batches = batches
1007
+
1008
+ assert len(self.batches) * self.batch_size == self.num_samples
1009
+ return iter(self.batches)
1010
+
1011
+ def _bisect(self, x, lo=0, hi=None):
1012
+ if hi is None:
1013
+ hi = len(self.boundaries) - 1
1014
+
1015
+ if hi > lo:
1016
+ mid = (hi + lo) // 2
1017
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
1018
+ return mid
1019
+ elif x <= self.boundaries[mid]:
1020
+ return self._bisect(x, lo, mid)
1021
+ else:
1022
+ return self._bisect(x, mid + 1, hi)
1023
+ else:
1024
+ return -1
1025
+
1026
+ def __len__(self):
1027
+ return self.num_samples // self.batch_size
GPT_SoVITS/module/losses.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+
5
+
6
+ def feature_loss(fmap_r, fmap_g):
7
+ loss = 0
8
+ for dr, dg in zip(fmap_r, fmap_g):
9
+ for rl, gl in zip(dr, dg):
10
+ rl = rl.float().detach()
11
+ gl = gl.float()
12
+ loss += torch.mean(torch.abs(rl - gl))
13
+
14
+ return loss * 2
15
+
16
+
17
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
18
+ loss = 0
19
+ r_losses = []
20
+ g_losses = []
21
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
22
+ dr = dr.float()
23
+ dg = dg.float()
24
+ r_loss = torch.mean((1 - dr) ** 2)
25
+ g_loss = torch.mean(dg**2)
26
+ loss += r_loss + g_loss
27
+ r_losses.append(r_loss.item())
28
+ g_losses.append(g_loss.item())
29
+
30
+ return loss, r_losses, g_losses
31
+
32
+
33
+ def generator_loss(disc_outputs):
34
+ loss = 0
35
+ gen_losses = []
36
+ for dg in disc_outputs:
37
+ dg = dg.float()
38
+ l = torch.mean((1 - dg) ** 2)
39
+ gen_losses.append(l)
40
+ loss += l
41
+
42
+ return loss, gen_losses
43
+
44
+
45
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
46
+ """
47
+ z_p, logs_q: [b, h, t_t]
48
+ m_p, logs_p: [b, h, t_t]
49
+ """
50
+ z_p = z_p.float()
51
+ logs_q = logs_q.float()
52
+ m_p = m_p.float()
53
+ logs_p = logs_p.float()
54
+ z_mask = z_mask.float()
55
+
56
+ kl = logs_p - logs_q - 0.5
57
+ kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)
58
+ kl = torch.sum(kl * z_mask)
59
+ l = kl / torch.sum(z_mask)
60
+ return l
61
+
62
+
63
+ def mle_loss(z, m, logs, logdet, mask):
64
+ l = torch.sum(logs) + 0.5 * torch.sum(
65
+ torch.exp(-2 * logs) * ((z - m) ** 2)
66
+ ) # neg normal likelihood w/o the constant term
67
+ l = l - torch.sum(logdet) # log jacobian determinant
68
+ l = l / torch.sum(torch.ones_like(z) * mask) # averaging across batch, channel and time axes
69
+ l = l + 0.5 * math.log(2 * math.pi) # add the remaining constant term
70
+ return l
GPT_SoVITS/module/mel_processing.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+
5
+ MAX_WAV_VALUE = 32768.0
6
+
7
+
8
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
9
+ """
10
+ PARAMS
11
+ ------
12
+ C: compression factor
13
+ """
14
+ return torch.log(torch.clamp(x, min=clip_val) * C)
15
+
16
+
17
+ def dynamic_range_decompression_torch(x, C=1):
18
+ """
19
+ PARAMS
20
+ ------
21
+ C: compression factor used to compress
22
+ """
23
+ return torch.exp(x) / C
24
+
25
+
26
+ def spectral_normalize_torch(magnitudes):
27
+ output = dynamic_range_compression_torch(magnitudes)
28
+ return output
29
+
30
+
31
+ def spectral_de_normalize_torch(magnitudes):
32
+ output = dynamic_range_decompression_torch(magnitudes)
33
+ return output
34
+
35
+
36
+ mel_basis = {}
37
+ hann_window = {}
38
+
39
+
40
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
41
+ if torch.min(y) < -1.2:
42
+ print('min value is ', torch.min(y))
43
+ if torch.max(y) > 1.2:
44
+ print('max value is ', torch.max(y))
45
+
46
+ global hann_window
47
+ dtype_device = str(y.dtype) + '_' + str(y.device)
48
+ # wnsize_dtype_device = str(win_size) + '_' + dtype_device
49
+ key = "%s-%s-%s-%s-%s" %(dtype_device,n_fft, sampling_rate, hop_size, win_size)
50
+ # if wnsize_dtype_device not in hann_window:
51
+ if key not in hann_window:
52
+ # hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
53
+ hann_window[key] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
54
+
55
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
56
+ y = y.squeeze(1)
57
+ # spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
58
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[key],
59
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
60
+
61
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-8)
62
+ return spec
63
+
64
+
65
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
66
+ global mel_basis
67
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
68
+ # fmax_dtype_device = str(fmax) + '_' + dtype_device
69
+ key = "%s-%s-%s-%s-%s-%s"%(dtype_device,n_fft, num_mels, sampling_rate, fmin, fmax)
70
+ # if fmax_dtype_device not in mel_basis:
71
+ if key not in mel_basis:
72
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
73
+ # mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
74
+ mel_basis[key] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
75
+ # spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
76
+ spec = torch.matmul(mel_basis[key], spec)
77
+ spec = spectral_normalize_torch(spec)
78
+ return spec
79
+
80
+
81
+
82
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
83
+ if torch.min(y) < -1.2:
84
+ print('min value is ', torch.min(y))
85
+ if torch.max(y) > 1.2:
86
+ print('max value is ', torch.max(y))
87
+
88
+ global mel_basis, hann_window
89
+ dtype_device = str(y.dtype) + '_' + str(y.device)
90
+ # fmax_dtype_device = str(fmax) + '_' + dtype_device
91
+ fmax_dtype_device = "%s-%s-%s-%s-%s-%s-%s-%s"%(dtype_device,n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax)
92
+ # wnsize_dtype_device = str(win_size) + '_' + dtype_device
93
+ wnsize_dtype_device = fmax_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-8)
107
+
108
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
109
+ spec = spectral_normalize_torch(spec)
110
+
111
+ return spec
GPT_SoVITS/module/models.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ warnings.filterwarnings("ignore")
4
+ import math
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+
10
+ from module import commons
11
+ from module import modules
12
+ from module import attentions
13
+ from f5_tts.model import DiT
14
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
15
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
16
+ from module.commons import init_weights, get_padding
17
+ from module.mrte_model import MRTE
18
+ from module.quantize import ResidualVectorQuantizer
19
+
20
+ # from text import symbols
21
+ from text import symbols as symbols_v1
22
+ from text import symbols2 as symbols_v2
23
+ from torch.cuda.amp import autocast
24
+ import contextlib
25
+ import random
26
+
27
+
28
+ class StochasticDurationPredictor(nn.Module):
29
+ def __init__(
30
+ self,
31
+ in_channels,
32
+ filter_channels,
33
+ kernel_size,
34
+ p_dropout,
35
+ n_flows=4,
36
+ gin_channels=0,
37
+ ):
38
+ super().__init__()
39
+ filter_channels = in_channels # it needs to be removed from future version.
40
+ self.in_channels = in_channels
41
+ self.filter_channels = filter_channels
42
+ self.kernel_size = kernel_size
43
+ self.p_dropout = p_dropout
44
+ self.n_flows = n_flows
45
+ self.gin_channels = gin_channels
46
+
47
+ self.log_flow = modules.Log()
48
+ self.flows = nn.ModuleList()
49
+ self.flows.append(modules.ElementwiseAffine(2))
50
+ for i in range(n_flows):
51
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
52
+ self.flows.append(modules.Flip())
53
+
54
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
55
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
56
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
57
+ self.post_flows = nn.ModuleList()
58
+ self.post_flows.append(modules.ElementwiseAffine(2))
59
+ for i in range(4):
60
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
61
+ self.post_flows.append(modules.Flip())
62
+
63
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
64
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
65
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
66
+ if gin_channels != 0:
67
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
68
+
69
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
70
+ x = torch.detach(x)
71
+ x = self.pre(x)
72
+ if g is not None:
73
+ g = torch.detach(g)
74
+ x = x + self.cond(g)
75
+ x = self.convs(x, x_mask)
76
+ x = self.proj(x) * x_mask
77
+
78
+ if not reverse:
79
+ flows = self.flows
80
+ assert w is not None
81
+
82
+ logdet_tot_q = 0
83
+ h_w = self.post_pre(w)
84
+ h_w = self.post_convs(h_w, x_mask)
85
+ h_w = self.post_proj(h_w) * x_mask
86
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
87
+ z_q = e_q
88
+ for flow in self.post_flows:
89
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
90
+ logdet_tot_q += logdet_q
91
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
92
+ u = torch.sigmoid(z_u) * x_mask
93
+ z0 = (w - u) * x_mask
94
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
95
+ logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2]) - logdet_tot_q
96
+
97
+ logdet_tot = 0
98
+ z0, logdet = self.log_flow(z0, x_mask)
99
+ logdet_tot += logdet
100
+ z = torch.cat([z0, z1], 1)
101
+ for flow in flows:
102
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
103
+ logdet_tot = logdet_tot + logdet
104
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2]) - logdet_tot
105
+ return nll + logq # [b]
106
+ else:
107
+ flows = list(reversed(self.flows))
108
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
109
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
110
+ for flow in flows:
111
+ z = flow(z, x_mask, g=x, reverse=reverse)
112
+ z0, z1 = torch.split(z, [1, 1], 1)
113
+ logw = z0
114
+ return logw
115
+
116
+
117
+ class DurationPredictor(nn.Module):
118
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
119
+ super().__init__()
120
+
121
+ self.in_channels = in_channels
122
+ self.filter_channels = filter_channels
123
+ self.kernel_size = kernel_size
124
+ self.p_dropout = p_dropout
125
+ self.gin_channels = gin_channels
126
+
127
+ self.drop = nn.Dropout(p_dropout)
128
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
129
+ self.norm_1 = modules.LayerNorm(filter_channels)
130
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
131
+ self.norm_2 = modules.LayerNorm(filter_channels)
132
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
133
+
134
+ if gin_channels != 0:
135
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
136
+
137
+ def forward(self, x, x_mask, g=None):
138
+ x = torch.detach(x)
139
+ if g is not None:
140
+ g = torch.detach(g)
141
+ x = x + self.cond(g)
142
+ x = self.conv_1(x * x_mask)
143
+ x = torch.relu(x)
144
+ x = self.norm_1(x)
145
+ x = self.drop(x)
146
+ x = self.conv_2(x * x_mask)
147
+ x = torch.relu(x)
148
+ x = self.norm_2(x)
149
+ x = self.drop(x)
150
+ x = self.proj(x * x_mask)
151
+ return x * x_mask
152
+
153
+
154
+ class TextEncoder(nn.Module):
155
+ def __init__(
156
+ self,
157
+ out_channels,
158
+ hidden_channels,
159
+ filter_channels,
160
+ n_heads,
161
+ n_layers,
162
+ kernel_size,
163
+ p_dropout,
164
+ latent_channels=192,
165
+ version="v2",
166
+ ):
167
+ super().__init__()
168
+ self.out_channels = out_channels
169
+ self.hidden_channels = hidden_channels
170
+ self.filter_channels = filter_channels
171
+ self.n_heads = n_heads
172
+ self.n_layers = n_layers
173
+ self.kernel_size = kernel_size
174
+ self.p_dropout = p_dropout
175
+ self.latent_channels = latent_channels
176
+ self.version = version
177
+
178
+ self.ssl_proj = nn.Conv1d(768, hidden_channels, 1)
179
+
180
+ self.encoder_ssl = attentions.Encoder(
181
+ hidden_channels,
182
+ filter_channels,
183
+ n_heads,
184
+ n_layers // 2,
185
+ kernel_size,
186
+ p_dropout,
187
+ )
188
+
189
+ self.encoder_text = attentions.Encoder(
190
+ hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
191
+ )
192
+
193
+ if self.version == "v1":
194
+ symbols = symbols_v1.symbols
195
+ else:
196
+ symbols = symbols_v2.symbols
197
+ self.text_embedding = nn.Embedding(len(symbols), hidden_channels)
198
+
199
+ self.mrte = MRTE()
200
+
201
+ self.encoder2 = attentions.Encoder(
202
+ hidden_channels,
203
+ filter_channels,
204
+ n_heads,
205
+ n_layers // 2,
206
+ kernel_size,
207
+ p_dropout,
208
+ )
209
+
210
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
211
+
212
+ def forward(self, y, y_lengths, text, text_lengths, ge, speed=1, test=None):
213
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
214
+
215
+ y = self.ssl_proj(y * y_mask) * y_mask
216
+
217
+ y = self.encoder_ssl(y * y_mask, y_mask)
218
+
219
+ text_mask = torch.unsqueeze(commons.sequence_mask(text_lengths, text.size(1)), 1).to(y.dtype)
220
+ if test == 1:
221
+ text[:, :] = 0
222
+ text = self.text_embedding(text).transpose(1, 2)
223
+ text = self.encoder_text(text * text_mask, text_mask)
224
+ y = self.mrte(y, y_mask, text, text_mask, ge)
225
+ y = self.encoder2(y * y_mask, y_mask)
226
+ if speed != 1:
227
+ y = F.interpolate(y, size=int(y.shape[-1] / speed) + 1, mode="linear")
228
+ y_mask = F.interpolate(y_mask, size=y.shape[-1], mode="nearest")
229
+ stats = self.proj(y) * y_mask
230
+ m, logs = torch.split(stats, self.out_channels, dim=1)
231
+ return y, m, logs, y_mask
232
+
233
+ def extract_latent(self, x):
234
+ x = self.ssl_proj(x)
235
+ quantized, codes, commit_loss, quantized_list = self.quantizer(x)
236
+ return codes.transpose(0, 1)
237
+
238
+ def decode_latent(self, codes, y_mask, refer, refer_mask, ge):
239
+ quantized = self.quantizer.decode(codes)
240
+
241
+ y = self.vq_proj(quantized) * y_mask
242
+ y = self.encoder_ssl(y * y_mask, y_mask)
243
+
244
+ y = self.mrte(y, y_mask, refer, refer_mask, ge)
245
+
246
+ y = self.encoder2(y * y_mask, y_mask)
247
+
248
+ stats = self.proj(y) * y_mask
249
+ m, logs = torch.split(stats, self.out_channels, dim=1)
250
+ return y, m, logs, y_mask, quantized
251
+
252
+
253
+ class ResidualCouplingBlock(nn.Module):
254
+ def __init__(
255
+ self,
256
+ channels,
257
+ hidden_channels,
258
+ kernel_size,
259
+ dilation_rate,
260
+ n_layers,
261
+ n_flows=4,
262
+ gin_channels=0,
263
+ ):
264
+ super().__init__()
265
+ self.channels = channels
266
+ self.hidden_channels = hidden_channels
267
+ self.kernel_size = kernel_size
268
+ self.dilation_rate = dilation_rate
269
+ self.n_layers = n_layers
270
+ self.n_flows = n_flows
271
+ self.gin_channels = gin_channels
272
+
273
+ self.flows = nn.ModuleList()
274
+ for i in range(n_flows):
275
+ self.flows.append(
276
+ modules.ResidualCouplingLayer(
277
+ channels,
278
+ hidden_channels,
279
+ kernel_size,
280
+ dilation_rate,
281
+ n_layers,
282
+ gin_channels=gin_channels,
283
+ mean_only=True,
284
+ )
285
+ )
286
+ self.flows.append(modules.Flip())
287
+
288
+ def forward(self, x, x_mask, g=None, reverse=False):
289
+ if not reverse:
290
+ for flow in self.flows:
291
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
292
+ else:
293
+ for flow in reversed(self.flows):
294
+ x = flow(x, x_mask, g=g, reverse=reverse)
295
+ return x
296
+
297
+
298
+ class PosteriorEncoder(nn.Module):
299
+ def __init__(
300
+ self,
301
+ in_channels,
302
+ out_channels,
303
+ hidden_channels,
304
+ kernel_size,
305
+ dilation_rate,
306
+ n_layers,
307
+ gin_channels=0,
308
+ ):
309
+ super().__init__()
310
+ self.in_channels = in_channels
311
+ self.out_channels = out_channels
312
+ self.hidden_channels = hidden_channels
313
+ self.kernel_size = kernel_size
314
+ self.dilation_rate = dilation_rate
315
+ self.n_layers = n_layers
316
+ self.gin_channels = gin_channels
317
+
318
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
319
+ self.enc = modules.WN(
320
+ hidden_channels,
321
+ kernel_size,
322
+ dilation_rate,
323
+ n_layers,
324
+ gin_channels=gin_channels,
325
+ )
326
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
327
+
328
+ def forward(self, x, x_lengths, g=None):
329
+ if g != None:
330
+ g = g.detach()
331
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
332
+ x = self.pre(x) * x_mask
333
+ x = self.enc(x, x_mask, g=g)
334
+ stats = self.proj(x) * x_mask
335
+ m, logs = torch.split(stats, self.out_channels, dim=1)
336
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
337
+ return z, m, logs, x_mask
338
+
339
+
340
+ class Encoder(nn.Module):
341
+ def __init__(
342
+ self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0
343
+ ):
344
+ super().__init__()
345
+ self.in_channels = in_channels
346
+ self.out_channels = out_channels
347
+ self.hidden_channels = hidden_channels
348
+ self.kernel_size = kernel_size
349
+ self.dilation_rate = dilation_rate
350
+ self.n_layers = n_layers
351
+ self.gin_channels = gin_channels
352
+
353
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
354
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
355
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
356
+
357
+ def forward(self, x, x_lengths, g=None):
358
+ if g != None:
359
+ g = g.detach()
360
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
361
+ x = self.pre(x) * x_mask
362
+ x = self.enc(x, x_mask, g=g)
363
+ stats = self.proj(x) * x_mask
364
+ return stats, x_mask
365
+
366
+
367
+ class WNEncoder(nn.Module):
368
+ def __init__(
369
+ self,
370
+ in_channels,
371
+ out_channels,
372
+ hidden_channels,
373
+ kernel_size,
374
+ dilation_rate,
375
+ n_layers,
376
+ gin_channels=0,
377
+ ):
378
+ super().__init__()
379
+ self.in_channels = in_channels
380
+ self.out_channels = out_channels
381
+ self.hidden_channels = hidden_channels
382
+ self.kernel_size = kernel_size
383
+ self.dilation_rate = dilation_rate
384
+ self.n_layers = n_layers
385
+ self.gin_channels = gin_channels
386
+
387
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
388
+ self.enc = modules.WN(
389
+ hidden_channels,
390
+ kernel_size,
391
+ dilation_rate,
392
+ n_layers,
393
+ gin_channels=gin_channels,
394
+ )
395
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
396
+ self.norm = modules.LayerNorm(out_channels)
397
+
398
+ def forward(self, x, x_lengths, g=None):
399
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
400
+ x = self.pre(x) * x_mask
401
+ x = self.enc(x, x_mask, g=g)
402
+ out = self.proj(x) * x_mask
403
+ out = self.norm(out)
404
+ return out
405
+
406
+
407
+ class Generator(torch.nn.Module):
408
+ def __init__(
409
+ self,
410
+ initial_channel,
411
+ resblock,
412
+ resblock_kernel_sizes,
413
+ resblock_dilation_sizes,
414
+ upsample_rates,
415
+ upsample_initial_channel,
416
+ upsample_kernel_sizes,
417
+ gin_channels=0,is_bias=False,
418
+ ):
419
+ super(Generator, self).__init__()
420
+ self.num_kernels = len(resblock_kernel_sizes)
421
+ self.num_upsamples = len(upsample_rates)
422
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
423
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
424
+
425
+ self.ups = nn.ModuleList()
426
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
427
+ self.ups.append(
428
+ weight_norm(
429
+ ConvTranspose1d(
430
+ upsample_initial_channel // (2**i),
431
+ upsample_initial_channel // (2 ** (i + 1)),
432
+ k,
433
+ u,
434
+ padding=(k - u) // 2,
435
+ )
436
+ )
437
+ )
438
+
439
+ self.resblocks = nn.ModuleList()
440
+ for i in range(len(self.ups)):
441
+ ch = upsample_initial_channel // (2 ** (i + 1))
442
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
443
+ self.resblocks.append(resblock(ch, k, d))
444
+
445
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=is_bias)
446
+ self.ups.apply(init_weights)
447
+
448
+ if gin_channels != 0:
449
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
450
+
451
+ def forward(self, x, g=None):
452
+ x = self.conv_pre(x)
453
+ if g is not None:
454
+ x = x + self.cond(g)
455
+
456
+ for i in range(self.num_upsamples):
457
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
458
+ x = self.ups[i](x)
459
+ xs = None
460
+ for j in range(self.num_kernels):
461
+ if xs is None:
462
+ xs = self.resblocks[i * self.num_kernels + j](x)
463
+ else:
464
+ xs += self.resblocks[i * self.num_kernels + j](x)
465
+ x = xs / self.num_kernels
466
+ x = F.leaky_relu(x)
467
+ x = self.conv_post(x)
468
+ x = torch.tanh(x)
469
+
470
+ return x
471
+
472
+ def remove_weight_norm(self):
473
+ print("Removing weight norm...")
474
+ for l in self.ups:
475
+ remove_weight_norm(l)
476
+ for l in self.resblocks:
477
+ l.remove_weight_norm()
478
+
479
+
480
+ class DiscriminatorP(torch.nn.Module):
481
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
482
+ super(DiscriminatorP, self).__init__()
483
+ self.period = period
484
+ self.use_spectral_norm = use_spectral_norm
485
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
486
+ self.convs = nn.ModuleList(
487
+ [
488
+ norm_f(
489
+ Conv2d(
490
+ 1,
491
+ 32,
492
+ (kernel_size, 1),
493
+ (stride, 1),
494
+ padding=(get_padding(kernel_size, 1), 0),
495
+ )
496
+ ),
497
+ norm_f(
498
+ Conv2d(
499
+ 32,
500
+ 128,
501
+ (kernel_size, 1),
502
+ (stride, 1),
503
+ padding=(get_padding(kernel_size, 1), 0),
504
+ )
505
+ ),
506
+ norm_f(
507
+ Conv2d(
508
+ 128,
509
+ 512,
510
+ (kernel_size, 1),
511
+ (stride, 1),
512
+ padding=(get_padding(kernel_size, 1), 0),
513
+ )
514
+ ),
515
+ norm_f(
516
+ Conv2d(
517
+ 512,
518
+ 1024,
519
+ (kernel_size, 1),
520
+ (stride, 1),
521
+ padding=(get_padding(kernel_size, 1), 0),
522
+ )
523
+ ),
524
+ norm_f(
525
+ Conv2d(
526
+ 1024,
527
+ 1024,
528
+ (kernel_size, 1),
529
+ 1,
530
+ padding=(get_padding(kernel_size, 1), 0),
531
+ )
532
+ ),
533
+ ]
534
+ )
535
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
536
+
537
+ def forward(self, x):
538
+ fmap = []
539
+
540
+ # 1d to 2d
541
+ b, c, t = x.shape
542
+ if t % self.period != 0: # pad first
543
+ n_pad = self.period - (t % self.period)
544
+ x = F.pad(x, (0, n_pad), "reflect")
545
+ t = t + n_pad
546
+ x = x.view(b, c, t // self.period, self.period)
547
+
548
+ for l in self.convs:
549
+ x = l(x)
550
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
551
+ fmap.append(x)
552
+ x = self.conv_post(x)
553
+ fmap.append(x)
554
+ x = torch.flatten(x, 1, -1)
555
+
556
+ return x, fmap
557
+
558
+
559
+ class DiscriminatorS(torch.nn.Module):
560
+ def __init__(self, use_spectral_norm=False):
561
+ super(DiscriminatorS, self).__init__()
562
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
563
+ self.convs = nn.ModuleList(
564
+ [
565
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
566
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
567
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
568
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
569
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
570
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
571
+ ]
572
+ )
573
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
574
+
575
+ def forward(self, x):
576
+ fmap = []
577
+
578
+ for l in self.convs:
579
+ x = l(x)
580
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
581
+ fmap.append(x)
582
+ x = self.conv_post(x)
583
+ fmap.append(x)
584
+ x = torch.flatten(x, 1, -1)
585
+
586
+ return x, fmap
587
+
588
+
589
+ class MultiPeriodDiscriminator(torch.nn.Module):
590
+ def __init__(self, use_spectral_norm=False):
591
+ super(MultiPeriodDiscriminator, self).__init__()
592
+ periods = [2, 3, 5, 7, 11]
593
+
594
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
595
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
596
+ self.discriminators = nn.ModuleList(discs)
597
+
598
+ def forward(self, y, y_hat):
599
+ y_d_rs = []
600
+ y_d_gs = []
601
+ fmap_rs = []
602
+ fmap_gs = []
603
+ for i, d in enumerate(self.discriminators):
604
+ y_d_r, fmap_r = d(y)
605
+ y_d_g, fmap_g = d(y_hat)
606
+ y_d_rs.append(y_d_r)
607
+ y_d_gs.append(y_d_g)
608
+ fmap_rs.append(fmap_r)
609
+ fmap_gs.append(fmap_g)
610
+
611
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
612
+
613
+
614
+ class ReferenceEncoder(nn.Module):
615
+ """
616
+ inputs --- [N, Ty/r, n_mels*r] mels
617
+ outputs --- [N, ref_enc_gru_size]
618
+ """
619
+
620
+ def __init__(self, spec_channels, gin_channels=0):
621
+ super().__init__()
622
+ self.spec_channels = spec_channels
623
+ ref_enc_filters = [32, 32, 64, 64, 128, 128]
624
+ K = len(ref_enc_filters)
625
+ filters = [1] + ref_enc_filters
626
+ convs = [
627
+ weight_norm(
628
+ nn.Conv2d(
629
+ in_channels=filters[i],
630
+ out_channels=filters[i + 1],
631
+ kernel_size=(3, 3),
632
+ stride=(2, 2),
633
+ padding=(1, 1),
634
+ )
635
+ )
636
+ for i in range(K)
637
+ ]
638
+ self.convs = nn.ModuleList(convs)
639
+ # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
640
+
641
+ out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
642
+ self.gru = nn.GRU(
643
+ input_size=ref_enc_filters[-1] * out_channels,
644
+ hidden_size=256 // 2,
645
+ batch_first=True,
646
+ )
647
+ self.proj = nn.Linear(128, gin_channels)
648
+
649
+ def forward(self, inputs):
650
+ N = inputs.size(0)
651
+ out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
652
+ for conv in self.convs:
653
+ out = conv(out)
654
+ # out = wn(out)
655
+ out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
656
+
657
+ out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
658
+ T = out.size(1)
659
+ N = out.size(0)
660
+ out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
661
+
662
+ self.gru.flatten_parameters()
663
+ memory, out = self.gru(out) # out --- [1, N, 128]
664
+
665
+ return self.proj(out.squeeze(0)).unsqueeze(-1)
666
+
667
+ def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
668
+ for i in range(n_convs):
669
+ L = (L - kernel_size + 2 * pad) // stride + 1
670
+ return L
671
+
672
+
673
+ class Quantizer_module(torch.nn.Module):
674
+ def __init__(self, n_e, e_dim):
675
+ super(Quantizer_module, self).__init__()
676
+ self.embedding = nn.Embedding(n_e, e_dim)
677
+ self.embedding.weight.data.uniform_(-1.0 / n_e, 1.0 / n_e)
678
+
679
+ def forward(self, x):
680
+ d = (
681
+ torch.sum(x**2, 1, keepdim=True)
682
+ + torch.sum(self.embedding.weight**2, 1)
683
+ - 2 * torch.matmul(x, self.embedding.weight.T)
684
+ )
685
+ min_indicies = torch.argmin(d, 1)
686
+ z_q = self.embedding(min_indicies)
687
+ return z_q, min_indicies
688
+
689
+
690
+ class Quantizer(torch.nn.Module):
691
+ def __init__(self, embed_dim=512, n_code_groups=4, n_codes=160):
692
+ super(Quantizer, self).__init__()
693
+ assert embed_dim % n_code_groups == 0
694
+ self.quantizer_modules = nn.ModuleList(
695
+ [Quantizer_module(n_codes, embed_dim // n_code_groups) for _ in range(n_code_groups)]
696
+ )
697
+ self.n_code_groups = n_code_groups
698
+ self.embed_dim = embed_dim
699
+
700
+ def forward(self, xin):
701
+ # B, C, T
702
+ B, C, T = xin.shape
703
+ xin = xin.transpose(1, 2)
704
+ x = xin.reshape(-1, self.embed_dim)
705
+ x = torch.split(x, self.embed_dim // self.n_code_groups, dim=-1)
706
+ min_indicies = []
707
+ z_q = []
708
+ for _x, m in zip(x, self.quantizer_modules):
709
+ _z_q, _min_indicies = m(_x)
710
+ z_q.append(_z_q)
711
+ min_indicies.append(_min_indicies) # B * T,
712
+ z_q = torch.cat(z_q, -1).reshape(xin.shape)
713
+ loss = 0.25 * torch.mean((z_q.detach() - xin) ** 2) + torch.mean((z_q - xin.detach()) ** 2)
714
+ z_q = xin + (z_q - xin).detach()
715
+ z_q = z_q.transpose(1, 2)
716
+ codes = torch.stack(min_indicies, -1).reshape(B, T, self.n_code_groups)
717
+ return z_q, loss, codes.transpose(1, 2)
718
+
719
+ def embed(self, x):
720
+ # idx: N, 4, T
721
+ x = x.transpose(1, 2)
722
+ x = torch.split(x, 1, 2)
723
+ ret = []
724
+ for q, embed in zip(x, self.quantizer_modules):
725
+ q = embed.embedding(q.squeeze(-1))
726
+ ret.append(q)
727
+ ret = torch.cat(ret, -1)
728
+ return ret.transpose(1, 2) # N, C, T
729
+
730
+
731
+ class CodePredictor(nn.Module):
732
+ def __init__(
733
+ self,
734
+ hidden_channels,
735
+ filter_channels,
736
+ n_heads,
737
+ n_layers,
738
+ kernel_size,
739
+ p_dropout,
740
+ n_q=8,
741
+ dims=1024,
742
+ ssl_dim=768,
743
+ ):
744
+ super().__init__()
745
+ self.hidden_channels = hidden_channels
746
+ self.filter_channels = filter_channels
747
+ self.n_heads = n_heads
748
+ self.n_layers = n_layers
749
+ self.kernel_size = kernel_size
750
+ self.p_dropout = p_dropout
751
+
752
+ self.vq_proj = nn.Conv1d(ssl_dim, hidden_channels, 1)
753
+ self.ref_enc = modules.MelStyleEncoder(ssl_dim, style_vector_dim=hidden_channels)
754
+
755
+ self.encoder = attentions.Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout)
756
+
757
+ self.out_proj = nn.Conv1d(hidden_channels, (n_q - 1) * dims, 1)
758
+ self.n_q = n_q
759
+ self.dims = dims
760
+
761
+ def forward(self, x, x_mask, refer, codes, infer=False):
762
+ x = x.detach()
763
+ x = self.vq_proj(x * x_mask) * x_mask
764
+ g = self.ref_enc(refer, x_mask)
765
+ x = x + g
766
+ x = self.encoder(x * x_mask, x_mask)
767
+ x = self.out_proj(x * x_mask) * x_mask
768
+ logits = x.reshape(x.shape[0], self.n_q - 1, self.dims, x.shape[-1]).transpose(2, 3)
769
+ target = codes[1:].transpose(0, 1)
770
+ if not infer:
771
+ logits = logits.reshape(-1, self.dims)
772
+ target = target.reshape(-1)
773
+ loss = torch.nn.functional.cross_entropy(logits, target)
774
+ return loss
775
+ else:
776
+ _, top10_preds = torch.topk(logits, 10, dim=-1)
777
+ correct_top10 = torch.any(top10_preds == target.unsqueeze(-1), dim=-1)
778
+ top3_acc = 100 * torch.mean(correct_top10.float()).detach().cpu().item()
779
+
780
+ print("Top-10 Accuracy:", top3_acc, "%")
781
+
782
+ pred_codes = torch.argmax(logits, dim=-1)
783
+ acc = 100 * torch.mean((pred_codes == target).float()).detach().cpu().item()
784
+ print("Top-1 Accuracy:", acc, "%")
785
+
786
+ return pred_codes.transpose(0, 1)
787
+
788
+
789
+ class SynthesizerTrn(nn.Module):
790
+ """
791
+ Synthesizer for Training
792
+ """
793
+
794
+ def __init__(
795
+ self,
796
+ spec_channels,
797
+ segment_size,
798
+ inter_channels,
799
+ hidden_channels,
800
+ filter_channels,
801
+ n_heads,
802
+ n_layers,
803
+ kernel_size,
804
+ p_dropout,
805
+ resblock,
806
+ resblock_kernel_sizes,
807
+ resblock_dilation_sizes,
808
+ upsample_rates,
809
+ upsample_initial_channel,
810
+ upsample_kernel_sizes,
811
+ n_speakers=0,
812
+ gin_channels=0,
813
+ use_sdp=True,
814
+ semantic_frame_rate=None,
815
+ freeze_quantizer=None,
816
+ version="v2",
817
+ **kwargs,
818
+ ):
819
+ super().__init__()
820
+ self.spec_channels = spec_channels
821
+ self.inter_channels = inter_channels
822
+ self.hidden_channels = hidden_channels
823
+ self.filter_channels = filter_channels
824
+ self.n_heads = n_heads
825
+ self.n_layers = n_layers
826
+ self.kernel_size = kernel_size
827
+ self.p_dropout = p_dropout
828
+ self.resblock = resblock
829
+ self.resblock_kernel_sizes = resblock_kernel_sizes
830
+ self.resblock_dilation_sizes = resblock_dilation_sizes
831
+ self.upsample_rates = upsample_rates
832
+ self.upsample_initial_channel = upsample_initial_channel
833
+ self.upsample_kernel_sizes = upsample_kernel_sizes
834
+ self.segment_size = segment_size
835
+ self.n_speakers = n_speakers
836
+ self.gin_channels = gin_channels
837
+ self.version = version
838
+
839
+ self.use_sdp = use_sdp
840
+ self.enc_p = TextEncoder(
841
+ inter_channels,
842
+ hidden_channels,
843
+ filter_channels,
844
+ n_heads,
845
+ n_layers,
846
+ kernel_size,
847
+ p_dropout,
848
+ version=version,
849
+ )
850
+ self.dec = Generator(
851
+ inter_channels,
852
+ resblock,
853
+ resblock_kernel_sizes,
854
+ resblock_dilation_sizes,
855
+ upsample_rates,
856
+ upsample_initial_channel,
857
+ upsample_kernel_sizes,
858
+ gin_channels=gin_channels,
859
+ )
860
+ self.enc_q = PosteriorEncoder(
861
+ spec_channels,
862
+ inter_channels,
863
+ hidden_channels,
864
+ 5,
865
+ 1,
866
+ 16,
867
+ gin_channels=gin_channels,
868
+ )
869
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
870
+
871
+ # self.version=os.environ.get("version","v1")
872
+ if self.version == "v1":
873
+ self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)
874
+ else:
875
+ self.ref_enc = modules.MelStyleEncoder(704, style_vector_dim=gin_channels)
876
+
877
+ ssl_dim = 768
878
+ assert semantic_frame_rate in ["25hz", "50hz"]
879
+ self.semantic_frame_rate = semantic_frame_rate
880
+ if semantic_frame_rate == "25hz":
881
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
882
+ else:
883
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
884
+
885
+ self.quantizer = ResidualVectorQuantizer(dimension=ssl_dim, n_q=1, bins=1024)
886
+ self.freeze_quantizer = freeze_quantizer
887
+
888
+ def forward(self, ssl, y, y_lengths, text, text_lengths):
889
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
890
+ if self.version == "v1":
891
+ ge = self.ref_enc(y * y_mask, y_mask)
892
+ else:
893
+ ge = self.ref_enc(y[:, :704] * y_mask, y_mask)
894
+ with autocast(enabled=False):
895
+ maybe_no_grad = torch.no_grad() if self.freeze_quantizer else contextlib.nullcontext()
896
+ with maybe_no_grad:
897
+ if self.freeze_quantizer:
898
+ self.ssl_proj.eval()
899
+ self.quantizer.eval()
900
+ ssl = self.ssl_proj(ssl)
901
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl, layers=[0])
902
+
903
+ if self.semantic_frame_rate == "25hz":
904
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
905
+
906
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
907
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=ge)
908
+ z_p = self.flow(z, y_mask, g=ge)
909
+
910
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
911
+ o = self.dec(z_slice, g=ge)
912
+ return (
913
+ o,
914
+ commit_loss,
915
+ ids_slice,
916
+ y_mask,
917
+ y_mask,
918
+ (z, z_p, m_p, logs_p, m_q, logs_q),
919
+ quantized,
920
+ )
921
+
922
+ def infer(self, ssl, y, y_lengths, text, text_lengths, test=None, noise_scale=0.5):
923
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
924
+ if self.version == "v1":
925
+ ge = self.ref_enc(y * y_mask, y_mask)
926
+ else:
927
+ ge = self.ref_enc(y[:, :704] * y_mask, y_mask)
928
+
929
+ ssl = self.ssl_proj(ssl)
930
+ quantized, codes, commit_loss, _ = self.quantizer(ssl, layers=[0])
931
+ if self.semantic_frame_rate == "25hz":
932
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
933
+
934
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge, test=test)
935
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
936
+
937
+ z = self.flow(z_p, y_mask, g=ge, reverse=True)
938
+
939
+ o = self.dec((z * y_mask)[:, :, :], g=ge)
940
+ return o, y_mask, (z, z_p, m_p, logs_p)
941
+
942
+ @torch.no_grad()
943
+ def decode(self, codes, text, refer, noise_scale=0.5, speed=1):
944
+ def get_ge(refer):
945
+ ge = None
946
+ if refer is not None:
947
+ refer_lengths = torch.LongTensor([refer.size(2)]).to(refer.device)
948
+ refer_mask = torch.unsqueeze(commons.sequence_mask(refer_lengths, refer.size(2)), 1).to(refer.dtype)
949
+ if self.version == "v1":
950
+ ge = self.ref_enc(refer * refer_mask, refer_mask)
951
+ else:
952
+ ge = self.ref_enc(refer[:, :704] * refer_mask, refer_mask)
953
+ return ge
954
+
955
+ if type(refer) == list:
956
+ ges = []
957
+ for _refer in refer:
958
+ ge = get_ge(_refer)
959
+ ges.append(ge)
960
+ ge = torch.stack(ges, 0).mean(0)
961
+ else:
962
+ ge = get_ge(refer)
963
+
964
+ y_lengths = torch.LongTensor([codes.size(2) * 2]).to(codes.device)
965
+ text_lengths = torch.LongTensor([text.size(-1)]).to(text.device)
966
+
967
+ quantized = self.quantizer.decode(codes)
968
+ if self.semantic_frame_rate == "25hz":
969
+ quantized = F.interpolate(quantized, size=int(quantized.shape[-1] * 2), mode="nearest")
970
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge, speed)
971
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
972
+
973
+ z = self.flow(z_p, y_mask, g=ge, reverse=True)
974
+
975
+ o = self.dec((z * y_mask)[:, :, :], g=ge)
976
+ return o
977
+
978
+ def extract_latent(self, x):
979
+ ssl = self.ssl_proj(x)
980
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
981
+ return codes.transpose(0, 1)
982
+
983
+
984
+ class CFM(torch.nn.Module):
985
+ def __init__(self, in_channels, dit):
986
+ super().__init__()
987
+ self.sigma_min = 1e-6
988
+
989
+ self.estimator = dit
990
+
991
+ self.in_channels = in_channels
992
+
993
+ self.criterion = torch.nn.MSELoss()
994
+
995
+ @torch.inference_mode()
996
+ def inference(self, mu, x_lens, prompt, n_timesteps, temperature=1.0, inference_cfg_rate=0):
997
+ """Forward diffusion"""
998
+ B, T = mu.size(0), mu.size(1)
999
+ x = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype) * temperature
1000
+ prompt_len = prompt.size(-1)
1001
+ prompt_x = torch.zeros_like(x, dtype=mu.dtype)
1002
+ prompt_x[..., :prompt_len] = prompt[..., :prompt_len]
1003
+ x[..., :prompt_len] = 0
1004
+ mu = mu.transpose(2, 1)
1005
+ t = 0
1006
+ d = 1 / n_timesteps
1007
+ for j in range(n_timesteps):
1008
+ t_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * t
1009
+ d_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * d
1010
+ # v_pred = model(x, t_tensor, d_tensor, **extra_args)
1011
+ v_pred = self.estimator(
1012
+ x, prompt_x, x_lens, t_tensor, d_tensor, mu, use_grad_ckpt=False, drop_audio_cond=False, drop_text=False
1013
+ ).transpose(2, 1)
1014
+ if inference_cfg_rate > 1e-5:
1015
+ neg = self.estimator(
1016
+ x,
1017
+ prompt_x,
1018
+ x_lens,
1019
+ t_tensor,
1020
+ d_tensor,
1021
+ mu,
1022
+ use_grad_ckpt=False,
1023
+ drop_audio_cond=True,
1024
+ drop_text=True,
1025
+ ).transpose(2, 1)
1026
+ v_pred = v_pred + (v_pred - neg) * inference_cfg_rate
1027
+ x = x + d * v_pred
1028
+ t = t + d
1029
+ x[:, :, :prompt_len] = 0
1030
+ return x
1031
+
1032
+ def forward(self, x1, x_lens, prompt_lens, mu, use_grad_ckpt):
1033
+ b, _, t = x1.shape
1034
+ t = torch.rand([b], device=mu.device, dtype=x1.dtype)
1035
+ x0 = torch.randn_like(x1, device=mu.device)
1036
+ vt = x1 - x0
1037
+ xt = x0 + t[:, None, None] * vt
1038
+ dt = torch.zeros_like(t, device=mu.device)
1039
+ prompt = torch.zeros_like(x1)
1040
+ for i in range(b):
1041
+ prompt[i, :, : prompt_lens[i]] = x1[i, :, : prompt_lens[i]]
1042
+ xt[i, :, : prompt_lens[i]] = 0
1043
+ gailv = 0.3 # if ttime()>1736250488 else 0.1
1044
+ if random.random() < gailv:
1045
+ base = torch.randint(2, 8, (t.shape[0],), device=mu.device)
1046
+ d = 1 / torch.pow(2, base)
1047
+ d_input = d.clone()
1048
+ d_input[d_input < 1e-2] = 0
1049
+ # with torch.no_grad():
1050
+ v_pred_1 = self.estimator(xt, prompt, x_lens, t, d_input, mu, use_grad_ckpt).transpose(2, 1).detach()
1051
+ # v_pred_1 = self.diffusion(xt, t, d_input, cond=conditioning).detach()
1052
+ x_mid = xt + d[:, None, None] * v_pred_1
1053
+ # v_pred_2 = self.diffusion(x_mid, t+d, d_input, cond=conditioning).detach()
1054
+ v_pred_2 = self.estimator(x_mid, prompt, x_lens, t + d, d_input, mu, use_grad_ckpt).transpose(2, 1).detach()
1055
+ vt = (v_pred_1 + v_pred_2) / 2
1056
+ vt = vt.detach()
1057
+ dt = 2 * d
1058
+
1059
+ vt_pred = self.estimator(xt, prompt, x_lens, t, dt, mu, use_grad_ckpt).transpose(2, 1)
1060
+ loss = 0
1061
+ for i in range(b):
1062
+ loss += self.criterion(vt_pred[i, :, prompt_lens[i] : x_lens[i]], vt[i, :, prompt_lens[i] : x_lens[i]])
1063
+ loss /= b
1064
+
1065
+ return loss
1066
+
1067
+
1068
+ def set_no_grad(net_g):
1069
+ for name, param in net_g.named_parameters():
1070
+ param.requires_grad = False
1071
+
1072
+
1073
+ class SynthesizerTrnV3(nn.Module):
1074
+ """
1075
+ Synthesizer for Training
1076
+ """
1077
+
1078
+ def __init__(
1079
+ self,
1080
+ spec_channels,
1081
+ segment_size,
1082
+ inter_channels,
1083
+ hidden_channels,
1084
+ filter_channels,
1085
+ n_heads,
1086
+ n_layers,
1087
+ kernel_size,
1088
+ p_dropout,
1089
+ resblock,
1090
+ resblock_kernel_sizes,
1091
+ resblock_dilation_sizes,
1092
+ upsample_rates,
1093
+ upsample_initial_channel,
1094
+ upsample_kernel_sizes,
1095
+ n_speakers=0,
1096
+ gin_channels=0,
1097
+ use_sdp=True,
1098
+ semantic_frame_rate=None,
1099
+ freeze_quantizer=None,
1100
+ version="v3",
1101
+ **kwargs,
1102
+ ):
1103
+ super().__init__()
1104
+ self.spec_channels = spec_channels
1105
+ self.inter_channels = inter_channels
1106
+ self.hidden_channels = hidden_channels
1107
+ self.filter_channels = filter_channels
1108
+ self.n_heads = n_heads
1109
+ self.n_layers = n_layers
1110
+ self.kernel_size = kernel_size
1111
+ self.p_dropout = p_dropout
1112
+ self.resblock = resblock
1113
+ self.resblock_kernel_sizes = resblock_kernel_sizes
1114
+ self.resblock_dilation_sizes = resblock_dilation_sizes
1115
+ self.upsample_rates = upsample_rates
1116
+ self.upsample_initial_channel = upsample_initial_channel
1117
+ self.upsample_kernel_sizes = upsample_kernel_sizes
1118
+ self.segment_size = segment_size
1119
+ self.n_speakers = n_speakers
1120
+ self.gin_channels = gin_channels
1121
+ self.version = version
1122
+
1123
+ self.model_dim = 512
1124
+ self.use_sdp = use_sdp
1125
+ self.enc_p = TextEncoder(
1126
+ inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
1127
+ )
1128
+ # self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)###Rollback
1129
+ self.ref_enc = modules.MelStyleEncoder(704, style_vector_dim=gin_channels) ###Rollback
1130
+ # self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
1131
+ # upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
1132
+ # self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
1133
+ # gin_channels=gin_channels)
1134
+ # self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
1135
+
1136
+ ssl_dim = 768
1137
+ assert semantic_frame_rate in ["25hz", "50hz"]
1138
+ self.semantic_frame_rate = semantic_frame_rate
1139
+ if semantic_frame_rate == "25hz":
1140
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
1141
+ else:
1142
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
1143
+
1144
+ self.quantizer = ResidualVectorQuantizer(dimension=ssl_dim, n_q=1, bins=1024)
1145
+ self.freeze_quantizer = freeze_quantizer
1146
+ inter_channels2 = 512
1147
+ self.bridge = nn.Sequential(nn.Conv1d(inter_channels, inter_channels2, 1, stride=1), nn.LeakyReLU())
1148
+ self.wns1 = Encoder(inter_channels2, inter_channels2, inter_channels2, 5, 1, 8, gin_channels=gin_channels)
1149
+ self.linear_mel = nn.Conv1d(inter_channels2, 100, 1, stride=1)
1150
+ self.cfm = CFM(
1151
+ 100,
1152
+ DiT(**dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=inter_channels2, conv_layers=4)),
1153
+ ) # text_dim is condition feature dim
1154
+ if self.freeze_quantizer == True:
1155
+ set_no_grad(self.ssl_proj)
1156
+ set_no_grad(self.quantizer)
1157
+ set_no_grad(self.enc_p)
1158
+
1159
+ def forward(
1160
+ self, ssl, y, mel, ssl_lengths, y_lengths, text, text_lengths, mel_lengths, use_grad_ckpt
1161
+ ): # ssl_lengths no need now
1162
+ with autocast(enabled=False):
1163
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
1164
+ ge = self.ref_enc(y[:, :704] * y_mask, y_mask)
1165
+ maybe_no_grad = torch.no_grad() if self.freeze_quantizer else contextlib.nullcontext()
1166
+ with maybe_no_grad:
1167
+ if self.freeze_quantizer:
1168
+ self.ssl_proj.eval() #
1169
+ self.quantizer.eval()
1170
+ self.enc_p.eval()
1171
+ ssl = self.ssl_proj(ssl)
1172
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl, layers=[0])
1173
+ quantized = F.interpolate(quantized, scale_factor=2, mode="nearest") ##BCT
1174
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
1175
+ fea = self.bridge(x)
1176
+ fea = F.interpolate(fea, scale_factor=(1.875 if self.version=="v3"else 2), mode="nearest") ##BCT
1177
+ fea, y_mask_ = self.wns1(
1178
+ fea, mel_lengths, ge
1179
+ ) ##If the 1-minute fine-tuning works fine, no need to manually adjust the learning rate.
1180
+ B = ssl.shape[0]
1181
+ prompt_len_max = mel_lengths * 2 / 3
1182
+ prompt_len = (torch.rand([B], device=fea.device) * prompt_len_max).floor().to(dtype=torch.long)
1183
+ minn = min(mel.shape[-1], fea.shape[-1])
1184
+ mel = mel[:, :, :minn]
1185
+ fea = fea[:, :, :minn]
1186
+ cfm_loss = self.cfm(mel, mel_lengths, prompt_len, fea, use_grad_ckpt)
1187
+ return cfm_loss
1188
+
1189
+ @torch.no_grad()
1190
+ def decode_encp(self, codes, text, refer, ge=None, speed=1):
1191
+ # print(2333333,refer.shape)
1192
+ # ge=None
1193
+ if ge == None:
1194
+ refer_lengths = torch.LongTensor([refer.size(2)]).to(refer.device)
1195
+ refer_mask = torch.unsqueeze(commons.sequence_mask(refer_lengths, refer.size(2)), 1).to(refer.dtype)
1196
+ ge = self.ref_enc(refer[:, :704] * refer_mask, refer_mask)
1197
+ y_lengths = torch.LongTensor([int(codes.size(2) * 2)]).to(codes.device)
1198
+ if speed == 1:
1199
+ sizee = int(codes.size(2) * (3.875 if self.version=="v3"else 4))
1200
+ else:
1201
+ sizee = int(codes.size(2) * (3.875 if self.version=="v3"else 4) / speed) + 1
1202
+ y_lengths1 = torch.LongTensor([sizee]).to(codes.device)
1203
+ text_lengths = torch.LongTensor([text.size(-1)]).to(text.device)
1204
+
1205
+ quantized = self.quantizer.decode(codes)
1206
+ if self.semantic_frame_rate == "25hz":
1207
+ quantized = F.interpolate(quantized, scale_factor=2, mode="nearest") ##BCT
1208
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge, speed)
1209
+ fea = self.bridge(x)
1210
+ fea = F.interpolate(fea, scale_factor=(1.875 if self.version=="v3"else 2), mode="nearest") ##BCT
1211
+ ####more wn paramter to learn mel
1212
+ fea, y_mask_ = self.wns1(fea, y_lengths1, ge)
1213
+ return fea, ge
1214
+
1215
+ def extract_latent(self, x):
1216
+ ssl = self.ssl_proj(x)
1217
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
1218
+ return codes.transpose(0, 1)
1219
+
1220
+
1221
+ class SynthesizerTrnV3b(nn.Module):
1222
+ """
1223
+ Synthesizer for Training
1224
+ """
1225
+
1226
+ def __init__(
1227
+ self,
1228
+ spec_channels,
1229
+ segment_size,
1230
+ inter_channels,
1231
+ hidden_channels,
1232
+ filter_channels,
1233
+ n_heads,
1234
+ n_layers,
1235
+ kernel_size,
1236
+ p_dropout,
1237
+ resblock,
1238
+ resblock_kernel_sizes,
1239
+ resblock_dilation_sizes,
1240
+ upsample_rates,
1241
+ upsample_initial_channel,
1242
+ upsample_kernel_sizes,
1243
+ n_speakers=0,
1244
+ gin_channels=0,
1245
+ use_sdp=True,
1246
+ semantic_frame_rate=None,
1247
+ freeze_quantizer=None,
1248
+ **kwargs,
1249
+ ):
1250
+ super().__init__()
1251
+ self.spec_channels = spec_channels
1252
+ self.inter_channels = inter_channels
1253
+ self.hidden_channels = hidden_channels
1254
+ self.filter_channels = filter_channels
1255
+ self.n_heads = n_heads
1256
+ self.n_layers = n_layers
1257
+ self.kernel_size = kernel_size
1258
+ self.p_dropout = p_dropout
1259
+ self.resblock = resblock
1260
+ self.resblock_kernel_sizes = resblock_kernel_sizes
1261
+ self.resblock_dilation_sizes = resblock_dilation_sizes
1262
+ self.upsample_rates = upsample_rates
1263
+ self.upsample_initial_channel = upsample_initial_channel
1264
+ self.upsample_kernel_sizes = upsample_kernel_sizes
1265
+ self.segment_size = segment_size
1266
+ self.n_speakers = n_speakers
1267
+ self.gin_channels = gin_channels
1268
+
1269
+ self.model_dim = 512
1270
+ self.use_sdp = use_sdp
1271
+ self.enc_p = TextEncoder(
1272
+ inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
1273
+ )
1274
+ # self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)###Rollback
1275
+ self.ref_enc = modules.MelStyleEncoder(704, style_vector_dim=gin_channels) ###Rollback
1276
+ self.dec = Generator(
1277
+ inter_channels,
1278
+ resblock,
1279
+ resblock_kernel_sizes,
1280
+ resblock_dilation_sizes,
1281
+ upsample_rates,
1282
+ upsample_initial_channel,
1283
+ upsample_kernel_sizes,
1284
+ gin_channels=gin_channels,
1285
+ )
1286
+ self.enc_q = PosteriorEncoder(
1287
+ spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels
1288
+ )
1289
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
1290
+
1291
+ ssl_dim = 768
1292
+ assert semantic_frame_rate in ["25hz", "50hz"]
1293
+ self.semantic_frame_rate = semantic_frame_rate
1294
+ if semantic_frame_rate == "25hz":
1295
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
1296
+ else:
1297
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
1298
+
1299
+ self.quantizer = ResidualVectorQuantizer(dimension=ssl_dim, n_q=1, bins=1024)
1300
+ self.freeze_quantizer = freeze_quantizer
1301
+
1302
+ inter_channels2 = 512
1303
+ self.bridge = nn.Sequential(nn.Conv1d(inter_channels, inter_channels2, 1, stride=1), nn.LeakyReLU())
1304
+ self.wns1 = Encoder(inter_channels2, inter_channels2, inter_channels2, 5, 1, 8, gin_channels=gin_channels)
1305
+ self.linear_mel = nn.Conv1d(inter_channels2, 100, 1, stride=1)
1306
+ self.cfm = CFM(
1307
+ 100,
1308
+ DiT(**dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=inter_channels2, conv_layers=4)),
1309
+ ) # text_dim is condition feature dim
1310
+
1311
+ def forward(self, ssl, y, mel, ssl_lengths, y_lengths, text, text_lengths, mel_lengths): # ssl_lengths no need now
1312
+ with autocast(enabled=False):
1313
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(2)), 1).to(y.dtype)
1314
+ ge = self.ref_enc(y[:, :704] * y_mask, y_mask)
1315
+ # ge = self.ref_enc(y * y_mask, y_mask)#change back, new spec setting is whole 24k
1316
+ # ge=None
1317
+ maybe_no_grad = torch.no_grad() if self.freeze_quantizer else contextlib.nullcontext()
1318
+ with maybe_no_grad:
1319
+ if self.freeze_quantizer:
1320
+ self.ssl_proj.eval()
1321
+ self.quantizer.eval()
1322
+ ssl = self.ssl_proj(ssl)
1323
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl, layers=[0])
1324
+ quantized = F.interpolate(quantized, scale_factor=2, mode="nearest") ##BCT
1325
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
1326
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=ge)
1327
+ z_p = self.flow(z, y_mask, g=ge)
1328
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
1329
+ o = self.dec(z_slice, g=ge)
1330
+ fea = self.bridge(x)
1331
+ fea = F.interpolate(fea, scale_factor=1.875, mode="nearest") ##BCT
1332
+ fea, y_mask_ = self.wns1(fea, mel_lengths, ge)
1333
+ learned_mel = self.linear_mel(fea)
1334
+ B = ssl.shape[0]
1335
+ prompt_len_max = mel_lengths * 2 / 3
1336
+ prompt_len = (torch.rand([B], device=fea.device) * prompt_len_max).floor().to(dtype=torch.long) #
1337
+ minn = min(mel.shape[-1], fea.shape[-1])
1338
+ mel = mel[:, :, :minn]
1339
+ fea = fea[:, :, :minn]
1340
+ cfm_loss = self.cfm(mel, mel_lengths, prompt_len, fea) # fea==cond,y_lengths==target_mel_lengths#ge not need
1341
+ return (
1342
+ commit_loss,
1343
+ cfm_loss,
1344
+ F.mse_loss(learned_mel, mel),
1345
+ o,
1346
+ ids_slice,
1347
+ y_mask,
1348
+ y_mask,
1349
+ (z, z_p, m_p, logs_p, m_q, logs_q),
1350
+ quantized,
1351
+ )
1352
+
1353
+ @torch.no_grad()
1354
+ def decode_encp(self, codes, text, refer, ge=None):
1355
+ # print(2333333,refer.shape)
1356
+ # ge=None
1357
+ if ge == None:
1358
+ refer_lengths = torch.LongTensor([refer.size(2)]).to(refer.device)
1359
+ refer_mask = torch.unsqueeze(commons.sequence_mask(refer_lengths, refer.size(2)), 1).to(refer.dtype)
1360
+ ge = self.ref_enc(refer[:, :704] * refer_mask, refer_mask)
1361
+ y_lengths = torch.LongTensor([int(codes.size(2) * 2)]).to(codes.device)
1362
+ y_lengths1 = torch.LongTensor([int(codes.size(2) * 2.5 * 1.5)]).to(codes.device)
1363
+ text_lengths = torch.LongTensor([text.size(-1)]).to(text.device)
1364
+
1365
+ quantized = self.quantizer.decode(codes)
1366
+ if self.semantic_frame_rate == "25hz":
1367
+ quantized = F.interpolate(quantized, scale_factor=2, mode="nearest") ##BCT
1368
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, y_lengths, text, text_lengths, ge)
1369
+ fea = self.bridge(x)
1370
+ fea = F.interpolate(fea, scale_factor=1.875, mode="nearest") ##BCT
1371
+ ####more wn paramter to learn mel
1372
+ fea, y_mask_ = self.wns1(fea, y_lengths1, ge)
1373
+ return fea, ge
1374
+
1375
+ def extract_latent(self, x):
1376
+ ssl = self.ssl_proj(x)
1377
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
1378
+ return codes.transpose(0, 1)
GPT_SoVITS/module/models_onnx.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional
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_onnx as attentions
10
+
11
+ from f5_tts.model import DiT
12
+
13
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
14
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
15
+ from module.commons import init_weights, get_padding
16
+ from module.quantize import ResidualVectorQuantizer
17
+
18
+ # from text import symbols
19
+ from text import symbols as symbols_v1
20
+ from text import symbols2 as symbols_v2
21
+
22
+
23
+ class StochasticDurationPredictor(nn.Module):
24
+ def __init__(
25
+ self,
26
+ in_channels,
27
+ filter_channels,
28
+ kernel_size,
29
+ p_dropout,
30
+ n_flows=4,
31
+ gin_channels=0,
32
+ ):
33
+ super().__init__()
34
+ filter_channels = in_channels # it needs to be removed from future version.
35
+ self.in_channels = in_channels
36
+ self.filter_channels = filter_channels
37
+ self.kernel_size = kernel_size
38
+ self.p_dropout = p_dropout
39
+ self.n_flows = n_flows
40
+ self.gin_channels = gin_channels
41
+
42
+ self.log_flow = modules.Log()
43
+ self.flows = nn.ModuleList()
44
+ self.flows.append(modules.ElementwiseAffine(2))
45
+ for i in range(n_flows):
46
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
47
+ self.flows.append(modules.Flip())
48
+
49
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
50
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
51
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
52
+ self.post_flows = nn.ModuleList()
53
+ self.post_flows.append(modules.ElementwiseAffine(2))
54
+ for i in range(4):
55
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
56
+ self.post_flows.append(modules.Flip())
57
+
58
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
59
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
60
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
61
+ if gin_channels != 0:
62
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
63
+
64
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
65
+ x = torch.detach(x)
66
+ x = self.pre(x)
67
+ if g is not None:
68
+ g = torch.detach(g)
69
+ x = x + self.cond(g)
70
+ x = self.convs(x, x_mask)
71
+ x = self.proj(x) * x_mask
72
+
73
+ if not reverse:
74
+ flows = self.flows
75
+ assert w is not None
76
+
77
+ logdet_tot_q = 0
78
+ h_w = self.post_pre(w)
79
+ h_w = self.post_convs(h_w, x_mask)
80
+ h_w = self.post_proj(h_w) * x_mask
81
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
82
+ z_q = e_q
83
+ for flow in self.post_flows:
84
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
85
+ logdet_tot_q += logdet_q
86
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
87
+ u = torch.sigmoid(z_u) * x_mask
88
+ z0 = (w - u) * x_mask
89
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
90
+ logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2]) - logdet_tot_q
91
+
92
+ logdet_tot = 0
93
+ z0, logdet = self.log_flow(z0, x_mask)
94
+ logdet_tot += logdet
95
+ z = torch.cat([z0, z1], 1)
96
+ for flow in flows:
97
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
98
+ logdet_tot = logdet_tot + logdet
99
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2]) - logdet_tot
100
+ return nll + logq # [b]
101
+ else:
102
+ flows = list(reversed(self.flows))
103
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
104
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
105
+ for flow in flows:
106
+ z = flow(z, x_mask, g=x, reverse=reverse)
107
+ z0, z1 = torch.split(z, [1, 1], 1)
108
+ logw = z0
109
+ return logw
110
+
111
+
112
+ class DurationPredictor(nn.Module):
113
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
114
+ super().__init__()
115
+
116
+ self.in_channels = in_channels
117
+ self.filter_channels = filter_channels
118
+ self.kernel_size = kernel_size
119
+ self.p_dropout = p_dropout
120
+ self.gin_channels = gin_channels
121
+
122
+ self.drop = nn.Dropout(p_dropout)
123
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
124
+ self.norm_1 = modules.LayerNorm(filter_channels)
125
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
126
+ self.norm_2 = modules.LayerNorm(filter_channels)
127
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
128
+
129
+ if gin_channels != 0:
130
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
131
+
132
+ def forward(self, x, x_mask, g=None):
133
+ x = torch.detach(x)
134
+ if g is not None:
135
+ g = torch.detach(g)
136
+ x = x + self.cond(g)
137
+ x = self.conv_1(x * x_mask)
138
+ x = torch.relu(x)
139
+ x = self.norm_1(x)
140
+ x = self.drop(x)
141
+ x = self.conv_2(x * x_mask)
142
+ x = torch.relu(x)
143
+ x = self.norm_2(x)
144
+ x = self.drop(x)
145
+ x = self.proj(x * x_mask)
146
+ return x * x_mask
147
+
148
+
149
+ class TextEncoder(nn.Module):
150
+ def __init__(
151
+ self,
152
+ out_channels,
153
+ hidden_channels,
154
+ filter_channels,
155
+ n_heads,
156
+ n_layers,
157
+ kernel_size,
158
+ p_dropout,
159
+ latent_channels=192,
160
+ version="v2",
161
+ ):
162
+ super().__init__()
163
+ self.out_channels = out_channels
164
+ self.hidden_channels = hidden_channels
165
+ self.filter_channels = filter_channels
166
+ self.n_heads = n_heads
167
+ self.n_layers = n_layers
168
+ self.kernel_size = kernel_size
169
+ self.p_dropout = p_dropout
170
+ self.latent_channels = latent_channels
171
+ self.version = version
172
+
173
+ self.ssl_proj = nn.Conv1d(768, hidden_channels, 1)
174
+
175
+ self.encoder_ssl = attentions.Encoder(
176
+ hidden_channels,
177
+ filter_channels,
178
+ n_heads,
179
+ n_layers // 2,
180
+ kernel_size,
181
+ p_dropout,
182
+ )
183
+
184
+ self.encoder_text = attentions.Encoder(
185
+ hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
186
+ )
187
+
188
+ if self.version == "v1":
189
+ symbols = symbols_v1.symbols
190
+ else:
191
+ symbols = symbols_v2.symbols
192
+ self.text_embedding = nn.Embedding(len(symbols), hidden_channels)
193
+
194
+ self.mrte = attentions.MRTE()
195
+
196
+ self.encoder2 = attentions.Encoder(
197
+ hidden_channels,
198
+ filter_channels,
199
+ n_heads,
200
+ n_layers // 2,
201
+ kernel_size,
202
+ p_dropout,
203
+ )
204
+
205
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
206
+
207
+ def forward(self, y, text, ge, speed=1):
208
+ y_mask = torch.ones_like(y[:1, :1, :])
209
+
210
+ y = self.ssl_proj(y * y_mask) * y_mask
211
+ y = self.encoder_ssl(y * y_mask, y_mask)
212
+
213
+ text_mask = torch.ones_like(text).to(y.dtype).unsqueeze(0)
214
+
215
+ text = self.text_embedding(text).transpose(1, 2)
216
+ text = self.encoder_text(text * text_mask, text_mask)
217
+ y = self.mrte(y, y_mask, text, text_mask, ge)
218
+
219
+ y = self.encoder2(y * y_mask, y_mask)
220
+ if speed != 1:
221
+ y = F.interpolate(y, size=int(y.shape[-1] / speed) + 1, mode="linear")
222
+ y_mask = F.interpolate(y_mask, size=y.shape[-1], mode="nearest")
223
+
224
+ stats = self.proj(y) * y_mask
225
+ m, logs = torch.split(stats, self.out_channels, dim=1)
226
+ return y, m, logs, y_mask
227
+
228
+
229
+ class ResidualCouplingBlock(nn.Module):
230
+ def __init__(
231
+ self,
232
+ channels,
233
+ hidden_channels,
234
+ kernel_size,
235
+ dilation_rate,
236
+ n_layers,
237
+ n_flows=4,
238
+ gin_channels=0,
239
+ ):
240
+ super().__init__()
241
+ self.channels = channels
242
+ self.hidden_channels = hidden_channels
243
+ self.kernel_size = kernel_size
244
+ self.dilation_rate = dilation_rate
245
+ self.n_layers = n_layers
246
+ self.n_flows = n_flows
247
+ self.gin_channels = gin_channels
248
+
249
+ self.flows = nn.ModuleList()
250
+ for i in range(n_flows):
251
+ self.flows.append(
252
+ modules.ResidualCouplingLayer(
253
+ channels,
254
+ hidden_channels,
255
+ kernel_size,
256
+ dilation_rate,
257
+ n_layers,
258
+ gin_channels=gin_channels,
259
+ mean_only=True,
260
+ )
261
+ )
262
+ self.flows.append(modules.Flip())
263
+
264
+ def forward(self, x, x_mask, g=None, reverse=False):
265
+ if not reverse:
266
+ for flow in self.flows:
267
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
268
+ else:
269
+ for flow in reversed(self.flows):
270
+ x = flow(x, x_mask, g=g, reverse=reverse)
271
+ return x
272
+
273
+
274
+ class PosteriorEncoder(nn.Module):
275
+ def __init__(
276
+ self,
277
+ in_channels,
278
+ out_channels,
279
+ hidden_channels,
280
+ kernel_size,
281
+ dilation_rate,
282
+ n_layers,
283
+ gin_channels=0,
284
+ ):
285
+ super().__init__()
286
+ self.in_channels = in_channels
287
+ self.out_channels = out_channels
288
+ self.hidden_channels = hidden_channels
289
+ self.kernel_size = kernel_size
290
+ self.dilation_rate = dilation_rate
291
+ self.n_layers = n_layers
292
+ self.gin_channels = gin_channels
293
+
294
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
295
+ self.enc = modules.WN(
296
+ hidden_channels,
297
+ kernel_size,
298
+ dilation_rate,
299
+ n_layers,
300
+ gin_channels=gin_channels,
301
+ )
302
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
303
+
304
+ def forward(self, x, x_lengths, g=None):
305
+ if g != None:
306
+ g = g.detach()
307
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
308
+ x = self.pre(x) * x_mask
309
+ x = self.enc(x, x_mask, g=g)
310
+ stats = self.proj(x) * x_mask
311
+ m, logs = torch.split(stats, self.out_channels, dim=1)
312
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
313
+ return z, m, logs, x_mask
314
+
315
+
316
+ class Encoder(nn.Module):
317
+ def __init__(
318
+ self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0
319
+ ):
320
+ super().__init__()
321
+ self.in_channels = in_channels
322
+ self.out_channels = out_channels
323
+ self.hidden_channels = hidden_channels
324
+ self.kernel_size = kernel_size
325
+ self.dilation_rate = dilation_rate
326
+ self.n_layers = n_layers
327
+ self.gin_channels = gin_channels
328
+
329
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
330
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
331
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
332
+
333
+ def forward(self, x, x_lengths, g=None):
334
+ if g != None:
335
+ g = g.detach()
336
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
337
+ x = self.pre(x) * x_mask
338
+ x = self.enc(x, x_mask, g=g)
339
+ stats = self.proj(x) * x_mask
340
+ return stats, x_mask
341
+
342
+
343
+ class WNEncoder(nn.Module):
344
+ def __init__(
345
+ self,
346
+ in_channels,
347
+ out_channels,
348
+ hidden_channels,
349
+ kernel_size,
350
+ dilation_rate,
351
+ n_layers,
352
+ gin_channels=0,
353
+ ):
354
+ super().__init__()
355
+ self.in_channels = in_channels
356
+ self.out_channels = out_channels
357
+ self.hidden_channels = hidden_channels
358
+ self.kernel_size = kernel_size
359
+ self.dilation_rate = dilation_rate
360
+ self.n_layers = n_layers
361
+ self.gin_channels = gin_channels
362
+
363
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
364
+ self.enc = modules.WN(
365
+ hidden_channels,
366
+ kernel_size,
367
+ dilation_rate,
368
+ n_layers,
369
+ gin_channels=gin_channels,
370
+ )
371
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
372
+ self.norm = modules.LayerNorm(out_channels)
373
+
374
+ def forward(self, x, x_lengths, g=None):
375
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
376
+ x = self.pre(x) * x_mask
377
+ x = self.enc(x, x_mask, g=g)
378
+ out = self.proj(x) * x_mask
379
+ out = self.norm(out)
380
+ return out
381
+
382
+
383
+ class Generator(torch.nn.Module):
384
+ def __init__(
385
+ self,
386
+ initial_channel,
387
+ resblock,
388
+ resblock_kernel_sizes,
389
+ resblock_dilation_sizes,
390
+ upsample_rates,
391
+ upsample_initial_channel,
392
+ upsample_kernel_sizes,
393
+ gin_channels=0,
394
+ ):
395
+ super(Generator, self).__init__()
396
+ self.num_kernels = len(resblock_kernel_sizes)
397
+ self.num_upsamples = len(upsample_rates)
398
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
399
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
400
+
401
+ self.ups = nn.ModuleList()
402
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
403
+ self.ups.append(
404
+ weight_norm(
405
+ ConvTranspose1d(
406
+ upsample_initial_channel // (2**i),
407
+ upsample_initial_channel // (2 ** (i + 1)),
408
+ k,
409
+ u,
410
+ padding=(k - u) // 2,
411
+ )
412
+ )
413
+ )
414
+
415
+ self.resblocks = nn.ModuleList()
416
+ for i in range(len(self.ups)):
417
+ ch = upsample_initial_channel // (2 ** (i + 1))
418
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
419
+ self.resblocks.append(resblock(ch, k, d))
420
+
421
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
422
+ self.ups.apply(init_weights)
423
+
424
+ if gin_channels != 0:
425
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
426
+
427
+ def forward(self, x, g: Optional[torch.Tensor] = None):
428
+ x = self.conv_pre(x)
429
+ if g is not None:
430
+ x = x + self.cond(g)
431
+
432
+ for i in range(self.num_upsamples):
433
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
434
+ x = self.ups[i](x)
435
+ xs = None
436
+ for j in range(self.num_kernels):
437
+ if xs is None:
438
+ xs = self.resblocks[i * self.num_kernels + j](x)
439
+ else:
440
+ xs += self.resblocks[i * self.num_kernels + j](x)
441
+ x = xs / self.num_kernels
442
+ x = F.leaky_relu(x)
443
+ x = self.conv_post(x)
444
+ x = torch.tanh(x)
445
+
446
+ return x
447
+
448
+ def remove_weight_norm(self):
449
+ print("Removing weight norm...")
450
+ for l in self.ups:
451
+ remove_weight_norm(l)
452
+ for l in self.resblocks:
453
+ l.remove_weight_norm()
454
+
455
+
456
+ class DiscriminatorP(torch.nn.Module):
457
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
458
+ super(DiscriminatorP, self).__init__()
459
+ self.period = period
460
+ self.use_spectral_norm = use_spectral_norm
461
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
462
+ self.convs = nn.ModuleList(
463
+ [
464
+ norm_f(
465
+ Conv2d(
466
+ 1,
467
+ 32,
468
+ (kernel_size, 1),
469
+ (stride, 1),
470
+ padding=(get_padding(kernel_size, 1), 0),
471
+ )
472
+ ),
473
+ norm_f(
474
+ Conv2d(
475
+ 32,
476
+ 128,
477
+ (kernel_size, 1),
478
+ (stride, 1),
479
+ padding=(get_padding(kernel_size, 1), 0),
480
+ )
481
+ ),
482
+ norm_f(
483
+ Conv2d(
484
+ 128,
485
+ 512,
486
+ (kernel_size, 1),
487
+ (stride, 1),
488
+ padding=(get_padding(kernel_size, 1), 0),
489
+ )
490
+ ),
491
+ norm_f(
492
+ Conv2d(
493
+ 512,
494
+ 1024,
495
+ (kernel_size, 1),
496
+ (stride, 1),
497
+ padding=(get_padding(kernel_size, 1), 0),
498
+ )
499
+ ),
500
+ norm_f(
501
+ Conv2d(
502
+ 1024,
503
+ 1024,
504
+ (kernel_size, 1),
505
+ 1,
506
+ padding=(get_padding(kernel_size, 1), 0),
507
+ )
508
+ ),
509
+ ]
510
+ )
511
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
512
+
513
+ def forward(self, x):
514
+ fmap = []
515
+
516
+ # 1d to 2d
517
+ b, c, t = x.shape
518
+ if t % self.period != 0: # pad first
519
+ n_pad = self.period - (t % self.period)
520
+ x = F.pad(x, (0, n_pad), "reflect")
521
+ t = t + n_pad
522
+ x = x.view(b, c, t // self.period, self.period)
523
+
524
+ for l in self.convs:
525
+ x = l(x)
526
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
527
+ fmap.append(x)
528
+ x = self.conv_post(x)
529
+ fmap.append(x)
530
+ x = torch.flatten(x, 1, -1)
531
+
532
+ return x, fmap
533
+
534
+
535
+ class DiscriminatorS(torch.nn.Module):
536
+ def __init__(self, use_spectral_norm=False):
537
+ super(DiscriminatorS, self).__init__()
538
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
539
+ self.convs = nn.ModuleList(
540
+ [
541
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
542
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
543
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
544
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
545
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
546
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
547
+ ]
548
+ )
549
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
550
+
551
+ def forward(self, x):
552
+ fmap = []
553
+
554
+ for l in self.convs:
555
+ x = l(x)
556
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
557
+ fmap.append(x)
558
+ x = self.conv_post(x)
559
+ fmap.append(x)
560
+ x = torch.flatten(x, 1, -1)
561
+
562
+ return x, fmap
563
+
564
+
565
+ class MultiPeriodDiscriminator(torch.nn.Module):
566
+ def __init__(self, use_spectral_norm=False):
567
+ super(MultiPeriodDiscriminator, self).__init__()
568
+ periods = [2, 3, 5, 7, 11]
569
+
570
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
571
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
572
+ self.discriminators = nn.ModuleList(discs)
573
+
574
+ def forward(self, y, y_hat):
575
+ y_d_rs = []
576
+ y_d_gs = []
577
+ fmap_rs = []
578
+ fmap_gs = []
579
+ for i, d in enumerate(self.discriminators):
580
+ y_d_r, fmap_r = d(y)
581
+ y_d_g, fmap_g = d(y_hat)
582
+ y_d_rs.append(y_d_r)
583
+ y_d_gs.append(y_d_g)
584
+ fmap_rs.append(fmap_r)
585
+ fmap_gs.append(fmap_g)
586
+
587
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
588
+
589
+
590
+ class ReferenceEncoder(nn.Module):
591
+ """
592
+ inputs --- [N, Ty/r, n_mels*r] mels
593
+ outputs --- [N, ref_enc_gru_size]
594
+ """
595
+
596
+ def __init__(self, spec_channels, gin_channels=0):
597
+ super().__init__()
598
+ self.spec_channels = spec_channels
599
+ ref_enc_filters = [32, 32, 64, 64, 128, 128]
600
+ K = len(ref_enc_filters)
601
+ filters = [1] + ref_enc_filters
602
+ convs = [
603
+ weight_norm(
604
+ nn.Conv2d(
605
+ in_channels=filters[i],
606
+ out_channels=filters[i + 1],
607
+ kernel_size=(3, 3),
608
+ stride=(2, 2),
609
+ padding=(1, 1),
610
+ )
611
+ )
612
+ for i in range(K)
613
+ ]
614
+ self.convs = nn.ModuleList(convs)
615
+ # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
616
+
617
+ out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
618
+ self.gru = nn.GRU(
619
+ input_size=ref_enc_filters[-1] * out_channels,
620
+ hidden_size=256 // 2,
621
+ batch_first=True,
622
+ )
623
+ self.proj = nn.Linear(128, gin_channels)
624
+
625
+ def forward(self, inputs):
626
+ N = inputs.size(0)
627
+ out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
628
+ for conv in self.convs:
629
+ out = conv(out)
630
+ # out = wn(out)
631
+ out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
632
+
633
+ out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
634
+ T = out.size(1)
635
+ N = out.size(0)
636
+ out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
637
+
638
+ self.gru.flatten_parameters()
639
+ memory, out = self.gru(out) # out --- [1, N, 128]
640
+
641
+ return self.proj(out.squeeze(0)).unsqueeze(-1)
642
+
643
+ def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
644
+ for i in range(n_convs):
645
+ L = (L - kernel_size + 2 * pad) // stride + 1
646
+ return L
647
+
648
+
649
+ class Quantizer_module(torch.nn.Module):
650
+ def __init__(self, n_e, e_dim):
651
+ super(Quantizer_module, self).__init__()
652
+ self.embedding = nn.Embedding(n_e, e_dim)
653
+ self.embedding.weight.data.uniform_(-1.0 / n_e, 1.0 / n_e)
654
+
655
+ def forward(self, x):
656
+ d = (
657
+ torch.sum(x**2, 1, keepdim=True)
658
+ + torch.sum(self.embedding.weight**2, 1)
659
+ - 2 * torch.matmul(x, self.embedding.weight.T)
660
+ )
661
+ min_indicies = torch.argmin(d, 1)
662
+ z_q = self.embedding(min_indicies)
663
+ return z_q, min_indicies
664
+
665
+
666
+ class Quantizer(torch.nn.Module):
667
+ def __init__(self, embed_dim=512, n_code_groups=4, n_codes=160):
668
+ super(Quantizer, self).__init__()
669
+ assert embed_dim % n_code_groups == 0
670
+ self.quantizer_modules = nn.ModuleList(
671
+ [Quantizer_module(n_codes, embed_dim // n_code_groups) for _ in range(n_code_groups)]
672
+ )
673
+ self.n_code_groups = n_code_groups
674
+ self.embed_dim = embed_dim
675
+
676
+ def forward(self, xin):
677
+ # B, C, T
678
+ B, C, T = xin.shape
679
+ xin = xin.transpose(1, 2)
680
+ x = xin.reshape(-1, self.embed_dim)
681
+ x = torch.split(x, self.embed_dim // self.n_code_groups, dim=-1)
682
+ min_indicies = []
683
+ z_q = []
684
+ for _x, m in zip(x, self.quantizer_modules):
685
+ _z_q, _min_indicies = m(_x)
686
+ z_q.append(_z_q)
687
+ min_indicies.append(_min_indicies) # B * T,
688
+ z_q = torch.cat(z_q, -1).reshape(xin.shape)
689
+ loss = 0.25 * torch.mean((z_q.detach() - xin) ** 2) + torch.mean((z_q - xin.detach()) ** 2)
690
+ z_q = xin + (z_q - xin).detach()
691
+ z_q = z_q.transpose(1, 2)
692
+ codes = torch.stack(min_indicies, -1).reshape(B, T, self.n_code_groups)
693
+ return z_q, loss, codes.transpose(1, 2)
694
+
695
+ def embed(self, x):
696
+ # idx: N, 4, T
697
+ x = x.transpose(1, 2)
698
+ x = torch.split(x, 1, 2)
699
+ ret = []
700
+ for q, embed in zip(x, self.quantizer_modules):
701
+ q = embed.embedding(q.squeeze(-1))
702
+ ret.append(q)
703
+ ret = torch.cat(ret, -1)
704
+ return ret.transpose(1, 2) # N, C, T
705
+
706
+
707
+ class CodePredictor(nn.Module):
708
+ def __init__(
709
+ self,
710
+ hidden_channels,
711
+ filter_channels,
712
+ n_heads,
713
+ n_layers,
714
+ kernel_size,
715
+ p_dropout,
716
+ n_q=8,
717
+ dims=1024,
718
+ ssl_dim=768,
719
+ ):
720
+ super().__init__()
721
+ self.hidden_channels = hidden_channels
722
+ self.filter_channels = filter_channels
723
+ self.n_heads = n_heads
724
+ self.n_layers = n_layers
725
+ self.kernel_size = kernel_size
726
+ self.p_dropout = p_dropout
727
+
728
+ self.vq_proj = nn.Conv1d(ssl_dim, hidden_channels, 1)
729
+ self.ref_enc = modules.MelStyleEncoder(ssl_dim, style_vector_dim=hidden_channels)
730
+
731
+ self.encoder = attentions.Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout)
732
+
733
+ self.out_proj = nn.Conv1d(hidden_channels, (n_q - 1) * dims, 1)
734
+ self.n_q = n_q
735
+ self.dims = dims
736
+
737
+ def forward(self, x, x_mask, refer, codes, infer=False):
738
+ x = x.detach()
739
+ x = self.vq_proj(x * x_mask) * x_mask
740
+ g = self.ref_enc(refer, x_mask)
741
+ x = x + g
742
+ x = self.encoder(x * x_mask, x_mask)
743
+ x = self.out_proj(x * x_mask) * x_mask
744
+ logits = x.reshape(x.shape[0], self.n_q - 1, self.dims, x.shape[-1]).transpose(2, 3)
745
+ target = codes[1:].transpose(0, 1)
746
+ if not infer:
747
+ logits = logits.reshape(-1, self.dims)
748
+ target = target.reshape(-1)
749
+ loss = torch.nn.functional.cross_entropy(logits, target)
750
+ return loss
751
+ else:
752
+ _, top10_preds = torch.topk(logits, 10, dim=-1)
753
+ correct_top10 = torch.any(top10_preds == target.unsqueeze(-1), dim=-1)
754
+ top3_acc = 100 * torch.mean(correct_top10.float()).detach().cpu().item()
755
+
756
+ print("Top-10 Accuracy:", top3_acc, "%")
757
+
758
+ pred_codes = torch.argmax(logits, dim=-1)
759
+ acc = 100 * torch.mean((pred_codes == target).float()).detach().cpu().item()
760
+ print("Top-1 Accuracy:", acc, "%")
761
+
762
+ return pred_codes.transpose(0, 1)
763
+
764
+
765
+ class SynthesizerTrn(nn.Module):
766
+ """
767
+ Synthesizer for Training
768
+ """
769
+
770
+ def __init__(
771
+ self,
772
+ spec_channels,
773
+ segment_size,
774
+ inter_channels,
775
+ hidden_channels,
776
+ filter_channels,
777
+ n_heads,
778
+ n_layers,
779
+ kernel_size,
780
+ p_dropout,
781
+ resblock,
782
+ resblock_kernel_sizes,
783
+ resblock_dilation_sizes,
784
+ upsample_rates,
785
+ upsample_initial_channel,
786
+ upsample_kernel_sizes,
787
+ n_speakers=0,
788
+ gin_channels=0,
789
+ use_sdp=True,
790
+ semantic_frame_rate=None,
791
+ freeze_quantizer=None,
792
+ version="v2",
793
+ **kwargs,
794
+ ):
795
+ super().__init__()
796
+ self.spec_channels = spec_channels
797
+ self.inter_channels = inter_channels
798
+ self.hidden_channels = hidden_channels
799
+ self.filter_channels = filter_channels
800
+ self.n_heads = n_heads
801
+ self.n_layers = n_layers
802
+ self.kernel_size = kernel_size
803
+ self.p_dropout = p_dropout
804
+ self.resblock = resblock
805
+ self.resblock_kernel_sizes = resblock_kernel_sizes
806
+ self.resblock_dilation_sizes = resblock_dilation_sizes
807
+ self.upsample_rates = upsample_rates
808
+ self.upsample_initial_channel = upsample_initial_channel
809
+ self.upsample_kernel_sizes = upsample_kernel_sizes
810
+ self.segment_size = segment_size
811
+ self.n_speakers = n_speakers
812
+ self.gin_channels = gin_channels
813
+ self.version = version
814
+
815
+ self.use_sdp = use_sdp
816
+ self.enc_p = TextEncoder(
817
+ inter_channels,
818
+ hidden_channels,
819
+ filter_channels,
820
+ n_heads,
821
+ n_layers,
822
+ kernel_size,
823
+ p_dropout,
824
+ version=version,
825
+ )
826
+ self.dec = Generator(
827
+ inter_channels,
828
+ resblock,
829
+ resblock_kernel_sizes,
830
+ resblock_dilation_sizes,
831
+ upsample_rates,
832
+ upsample_initial_channel,
833
+ upsample_kernel_sizes,
834
+ gin_channels=gin_channels,
835
+ )
836
+ # self.enc_q = PosteriorEncoder(
837
+ # spec_channels,
838
+ # inter_channels,
839
+ # hidden_channels,
840
+ # 5,
841
+ # 1,
842
+ # 16,
843
+ # gin_channels=gin_channels,
844
+ # )
845
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
846
+
847
+ # self.version=os.environ.get("version","v1")
848
+ if self.version == "v1":
849
+ self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)
850
+ else:
851
+ self.ref_enc = modules.MelStyleEncoder(704, style_vector_dim=gin_channels)
852
+
853
+ ssl_dim = 768
854
+ self.ssl_dim = ssl_dim
855
+ assert semantic_frame_rate in ["25hz", "50hz"]
856
+ self.semantic_frame_rate = semantic_frame_rate
857
+ if semantic_frame_rate == "25hz":
858
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
859
+ else:
860
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
861
+
862
+ self.quantizer = ResidualVectorQuantizer(dimension=ssl_dim, n_q=1, bins=1024)
863
+ if freeze_quantizer:
864
+ self.ssl_proj.requires_grad_(False)
865
+ self.quantizer.requires_grad_(False)
866
+ # self.enc_p.text_embedding.requires_grad_(False)
867
+ # self.enc_p.encoder_text.requires_grad_(False)
868
+ # self.enc_p.mrte.requires_grad_(False)
869
+
870
+ def forward(self, codes, text, refer, noise_scale=0.5, speed=1):
871
+ refer_mask = torch.ones_like(refer[:1, :1, :])
872
+ if self.version == "v1":
873
+ ge = self.ref_enc(refer * refer_mask, refer_mask)
874
+ else:
875
+ ge = self.ref_enc(refer[:, :704] * refer_mask, refer_mask)
876
+
877
+ quantized = self.quantizer.decode(codes)
878
+ if self.semantic_frame_rate == "25hz":
879
+ dquantized = torch.cat([quantized, quantized]).permute(1, 2, 0)
880
+ quantized = dquantized.contiguous().view(1, self.ssl_dim, -1)
881
+
882
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, text, ge, speed)
883
+
884
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
885
+
886
+ z = self.flow(z_p, y_mask, g=ge, reverse=True)
887
+
888
+ o = self.dec((z * y_mask)[:, :, :], g=ge)
889
+ return o
890
+
891
+ def extract_latent(self, x):
892
+ ssl = self.ssl_proj(x)
893
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
894
+ return codes.transpose(0, 1)
895
+
896
+
897
+ class CFM(torch.nn.Module):
898
+ def __init__(self, in_channels, dit):
899
+ super().__init__()
900
+ # self.sigma_min = 1e-6
901
+
902
+ self.estimator = dit
903
+
904
+ self.in_channels = in_channels
905
+
906
+ # self.criterion = torch.nn.MSELoss()
907
+
908
+ def forward(
909
+ self,
910
+ mu: torch.Tensor,
911
+ x_lens: torch.LongTensor,
912
+ prompt: torch.Tensor,
913
+ n_timesteps: torch.LongTensor,
914
+ temperature: float = 1.0,
915
+ ):
916
+ """Forward diffusion"""
917
+ B, T = mu.size(0), mu.size(1)
918
+ x = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype)
919
+
920
+ ntimesteps = int(n_timesteps)
921
+
922
+ prompt_len = prompt.size(-1)
923
+ prompt_x = torch.zeros_like(x, dtype=mu.dtype)
924
+ prompt_x[..., :prompt_len] = prompt[..., :prompt_len]
925
+ x[..., :prompt_len] = 0.0
926
+ mu = mu.transpose(2, 1)
927
+ t = torch.tensor(0.0, dtype=x.dtype, device=x.device)
928
+ d = torch.tensor(1.0 / ntimesteps, dtype=x.dtype, device=x.device)
929
+ d_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * d
930
+
931
+ for j in range(ntimesteps):
932
+ t_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * t
933
+ # d_tensor = torch.ones(x.shape[0], device=x.device,dtype=mu.dtype) * d
934
+ # v_pred = model(x, t_tensor, d_tensor, **extra_args)
935
+ v_pred = self.estimator(x, prompt_x, x_lens, t_tensor, d_tensor, mu).transpose(2, 1)
936
+ # if inference_cfg_rate>1e-5:
937
+ # neg = self.estimator(x, prompt_x, x_lens, t_tensor, d_tensor, mu, use_grad_ckpt=False, drop_audio_cond=True, drop_text=True).transpose(2, 1)
938
+ # v_pred=v_pred+(v_pred-neg)*inference_cfg_rate
939
+ x = x + d * v_pred
940
+ t = t + d
941
+ x[:, :, :prompt_len] = 0.0
942
+ return x
943
+
944
+
945
+ def set_no_grad(net_g):
946
+ for name, param in net_g.named_parameters():
947
+ param.requires_grad = False
948
+
949
+
950
+ @torch.jit.script_if_tracing
951
+ def compile_codes_length(codes):
952
+ y_lengths1 = torch.LongTensor([codes.size(2)]).to(codes.device)
953
+ return y_lengths1 * 2.5 * 1.5
954
+
955
+
956
+ @torch.jit.script_if_tracing
957
+ def compile_ref_length(refer):
958
+ refer_lengths = torch.LongTensor([refer.size(2)]).to(refer.device)
959
+ return refer_lengths
960
+
961
+
962
+ class SynthesizerTrnV3(nn.Module):
963
+ """
964
+ Synthesizer for Training
965
+ """
966
+
967
+ def __init__(
968
+ self,
969
+ spec_channels,
970
+ segment_size,
971
+ inter_channels,
972
+ hidden_channels,
973
+ filter_channels,
974
+ n_heads,
975
+ n_layers,
976
+ kernel_size,
977
+ p_dropout,
978
+ resblock,
979
+ resblock_kernel_sizes,
980
+ resblock_dilation_sizes,
981
+ upsample_rates,
982
+ upsample_initial_channel,
983
+ upsample_kernel_sizes,
984
+ n_speakers=0,
985
+ gin_channels=0,
986
+ use_sdp=True,
987
+ semantic_frame_rate=None,
988
+ freeze_quantizer=None,
989
+ version="v3",
990
+ **kwargs,
991
+ ):
992
+ super().__init__()
993
+ self.spec_channels = spec_channels
994
+ self.inter_channels = inter_channels
995
+ self.hidden_channels = hidden_channels
996
+ self.filter_channels = filter_channels
997
+ self.n_heads = n_heads
998
+ self.n_layers = n_layers
999
+ self.kernel_size = kernel_size
1000
+ self.p_dropout = p_dropout
1001
+ self.resblock = resblock
1002
+ self.resblock_kernel_sizes = resblock_kernel_sizes
1003
+ self.resblock_dilation_sizes = resblock_dilation_sizes
1004
+ self.upsample_rates = upsample_rates
1005
+ self.upsample_initial_channel = upsample_initial_channel
1006
+ self.upsample_kernel_sizes = upsample_kernel_sizes
1007
+ self.segment_size = segment_size
1008
+ self.n_speakers = n_speakers
1009
+ self.gin_channels = gin_channels
1010
+ self.version = version
1011
+
1012
+ self.model_dim = 512
1013
+ self.use_sdp = use_sdp
1014
+ self.enc_p = TextEncoder(
1015
+ inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
1016
+ )
1017
+ # self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels)###Rollback
1018
+ self.ref_enc = modules.MelStyleEncoder(704, style_vector_dim=gin_channels) ###Rollback
1019
+ # self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
1020
+ # upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
1021
+ # self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
1022
+ # gin_channels=gin_channels)
1023
+ # self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
1024
+
1025
+ ssl_dim = 768
1026
+ assert semantic_frame_rate in ["25hz", "50hz"]
1027
+ self.semantic_frame_rate = semantic_frame_rate
1028
+ if semantic_frame_rate == "25hz":
1029
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 2, stride=2)
1030
+ else:
1031
+ self.ssl_proj = nn.Conv1d(ssl_dim, ssl_dim, 1, stride=1)
1032
+
1033
+ self.quantizer = ResidualVectorQuantizer(dimension=ssl_dim, n_q=1, bins=1024)
1034
+ freeze_quantizer
1035
+ inter_channels2 = 512
1036
+ self.bridge = nn.Sequential(nn.Conv1d(inter_channels, inter_channels2, 1, stride=1), nn.LeakyReLU())
1037
+ self.wns1 = Encoder(inter_channels2, inter_channels2, inter_channels2, 5, 1, 8, gin_channels=gin_channels)
1038
+ self.linear_mel = nn.Conv1d(inter_channels2, 100, 1, stride=1)
1039
+ self.cfm = CFM(
1040
+ 100,
1041
+ DiT(**dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=inter_channels2, conv_layers=4)),
1042
+ ) # text_dim is condition feature dim
1043
+ if freeze_quantizer == True:
1044
+ set_no_grad(self.ssl_proj)
1045
+ set_no_grad(self.quantizer)
1046
+ set_no_grad(self.enc_p)
1047
+
1048
+ def create_ge(self, refer):
1049
+ refer_lengths = compile_ref_length(refer)
1050
+ refer_mask = torch.unsqueeze(commons.sequence_mask(refer_lengths, refer.size(2)), 1).to(refer.dtype)
1051
+ ge = self.ref_enc(refer[:, :704] * refer_mask, refer_mask)
1052
+ return ge
1053
+
1054
+ def forward(self, codes, text, ge, speed=1):
1055
+ y_lengths1 = compile_codes_length(codes)
1056
+
1057
+ quantized = self.quantizer.decode(codes)
1058
+ if self.semantic_frame_rate == "25hz":
1059
+ quantized = F.interpolate(quantized, scale_factor=2, mode="nearest") ##BCT
1060
+ x, m_p, logs_p, y_mask = self.enc_p(quantized, text, ge, speed)
1061
+ fea = self.bridge(x)
1062
+ fea = F.interpolate(fea, scale_factor=1.875, mode="nearest") ##BCT
1063
+ ####more wn paramter to learn mel
1064
+ fea, y_mask_ = self.wns1(fea, y_lengths1, ge)
1065
+ return fea
1066
+
1067
+ def extract_latent(self, x):
1068
+ ssl = self.ssl_proj(x)
1069
+ quantized, codes, commit_loss, quantized_list = self.quantizer(ssl)
1070
+ return codes.transpose(0, 1)
GPT_SoVITS/module/modules.py ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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__(
36
+ self,
37
+ in_channels,
38
+ hidden_channels,
39
+ out_channels,
40
+ kernel_size,
41
+ n_layers,
42
+ p_dropout,
43
+ ):
44
+ super().__init__()
45
+ self.in_channels = in_channels
46
+ self.hidden_channels = hidden_channels
47
+ self.out_channels = out_channels
48
+ self.kernel_size = kernel_size
49
+ self.n_layers = n_layers
50
+ self.p_dropout = p_dropout
51
+ assert n_layers > 1, "Number of layers should be larger than 0."
52
+
53
+ self.conv_layers = nn.ModuleList()
54
+ self.norm_layers = nn.ModuleList()
55
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size // 2))
56
+ self.norm_layers.append(LayerNorm(hidden_channels))
57
+ self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
58
+ for _ in range(n_layers - 1):
59
+ self.conv_layers.append(
60
+ nn.Conv1d(
61
+ hidden_channels,
62
+ hidden_channels,
63
+ kernel_size,
64
+ padding=kernel_size // 2,
65
+ )
66
+ )
67
+ self.norm_layers.append(LayerNorm(hidden_channels))
68
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
69
+ self.proj.weight.data.zero_()
70
+ self.proj.bias.data.zero_()
71
+
72
+ def forward(self, x, x_mask):
73
+ x_org = x
74
+ for i in range(self.n_layers):
75
+ x = self.conv_layers[i](x * x_mask)
76
+ x = self.norm_layers[i](x)
77
+ x = self.relu_drop(x)
78
+ x = x_org + self.proj(x)
79
+ return x * x_mask
80
+
81
+
82
+ class DDSConv(nn.Module):
83
+ """
84
+ Dialted and Depth-Separable Convolution
85
+ """
86
+
87
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
88
+ super().__init__()
89
+ self.channels = channels
90
+ self.kernel_size = kernel_size
91
+ self.n_layers = n_layers
92
+ self.p_dropout = p_dropout
93
+
94
+ self.drop = nn.Dropout(p_dropout)
95
+ self.convs_sep = nn.ModuleList()
96
+ self.convs_1x1 = nn.ModuleList()
97
+ self.norms_1 = nn.ModuleList()
98
+ self.norms_2 = nn.ModuleList()
99
+ for i in range(n_layers):
100
+ dilation = kernel_size**i
101
+ padding = (kernel_size * dilation - dilation) // 2
102
+ self.convs_sep.append(
103
+ nn.Conv1d(
104
+ channels,
105
+ channels,
106
+ kernel_size,
107
+ groups=channels,
108
+ dilation=dilation,
109
+ padding=padding,
110
+ )
111
+ )
112
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
113
+ self.norms_1.append(LayerNorm(channels))
114
+ self.norms_2.append(LayerNorm(channels))
115
+
116
+ def forward(self, x, x_mask, g=None):
117
+ if g is not None:
118
+ x = x + g
119
+ for i in range(self.n_layers):
120
+ y = self.convs_sep[i](x * x_mask)
121
+ y = self.norms_1[i](y)
122
+ y = F.gelu(y)
123
+ y = self.convs_1x1[i](y)
124
+ y = self.norms_2[i](y)
125
+ y = F.gelu(y)
126
+ y = self.drop(y)
127
+ x = x + y
128
+ return x * x_mask
129
+
130
+
131
+ class WN(torch.nn.Module):
132
+ def __init__(
133
+ self,
134
+ hidden_channels,
135
+ kernel_size,
136
+ dilation_rate,
137
+ n_layers,
138
+ gin_channels=0,
139
+ p_dropout=0,
140
+ ):
141
+ super(WN, self).__init__()
142
+ assert kernel_size % 2 == 1
143
+ self.hidden_channels = hidden_channels
144
+ self.kernel_size = (kernel_size,)
145
+ self.dilation_rate = dilation_rate
146
+ self.n_layers = n_layers
147
+ self.gin_channels = gin_channels
148
+ self.p_dropout = p_dropout
149
+
150
+ self.in_layers = torch.nn.ModuleList()
151
+ self.res_skip_layers = torch.nn.ModuleList()
152
+ self.drop = nn.Dropout(p_dropout)
153
+
154
+ if gin_channels != 0:
155
+ cond_layer = torch.nn.Conv1d(gin_channels, 2 * hidden_channels * n_layers, 1)
156
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
157
+
158
+ for i in range(n_layers):
159
+ dilation = dilation_rate**i
160
+ padding = int((kernel_size * dilation - dilation) / 2)
161
+ in_layer = torch.nn.Conv1d(
162
+ hidden_channels,
163
+ 2 * hidden_channels,
164
+ kernel_size,
165
+ dilation=dilation,
166
+ padding=padding,
167
+ )
168
+ in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
169
+ self.in_layers.append(in_layer)
170
+
171
+ # last one is not necessary
172
+ if i < n_layers - 1:
173
+ res_skip_channels = 2 * hidden_channels
174
+ else:
175
+ res_skip_channels = hidden_channels
176
+
177
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
178
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
179
+ self.res_skip_layers.append(res_skip_layer)
180
+
181
+ def forward(self, x, x_mask, g=None, **kwargs):
182
+ output = torch.zeros_like(x)
183
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
184
+
185
+ if g is not None:
186
+ g = self.cond_layer(g)
187
+
188
+ for i in range(self.n_layers):
189
+ x_in = self.in_layers[i](x)
190
+ if g is not None:
191
+ cond_offset = i * 2 * self.hidden_channels
192
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
193
+ else:
194
+ g_l = torch.zeros_like(x_in)
195
+
196
+ acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
197
+ acts = self.drop(acts)
198
+
199
+ res_skip_acts = self.res_skip_layers[i](acts)
200
+ if i < self.n_layers - 1:
201
+ res_acts = res_skip_acts[:, : self.hidden_channels, :]
202
+ x = (x + res_acts) * x_mask
203
+ output = output + res_skip_acts[:, self.hidden_channels :, :]
204
+ else:
205
+ output = output + res_skip_acts
206
+ return output * x_mask
207
+
208
+ def remove_weight_norm(self):
209
+ if self.gin_channels != 0:
210
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
211
+ for l in self.in_layers:
212
+ torch.nn.utils.remove_weight_norm(l)
213
+ for l in self.res_skip_layers:
214
+ torch.nn.utils.remove_weight_norm(l)
215
+
216
+
217
+ class ResBlock1(torch.nn.Module):
218
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
219
+ super(ResBlock1, self).__init__()
220
+ self.convs1 = nn.ModuleList(
221
+ [
222
+ weight_norm(
223
+ Conv1d(
224
+ channels,
225
+ channels,
226
+ kernel_size,
227
+ 1,
228
+ dilation=dilation[0],
229
+ padding=get_padding(kernel_size, dilation[0]),
230
+ )
231
+ ),
232
+ weight_norm(
233
+ Conv1d(
234
+ channels,
235
+ channels,
236
+ kernel_size,
237
+ 1,
238
+ dilation=dilation[1],
239
+ padding=get_padding(kernel_size, dilation[1]),
240
+ )
241
+ ),
242
+ weight_norm(
243
+ Conv1d(
244
+ channels,
245
+ channels,
246
+ kernel_size,
247
+ 1,
248
+ dilation=dilation[2],
249
+ padding=get_padding(kernel_size, dilation[2]),
250
+ )
251
+ ),
252
+ ]
253
+ )
254
+ self.convs1.apply(init_weights)
255
+
256
+ self.convs2 = nn.ModuleList(
257
+ [
258
+ weight_norm(
259
+ Conv1d(
260
+ channels,
261
+ channels,
262
+ kernel_size,
263
+ 1,
264
+ dilation=1,
265
+ padding=get_padding(kernel_size, 1),
266
+ )
267
+ ),
268
+ weight_norm(
269
+ Conv1d(
270
+ channels,
271
+ channels,
272
+ kernel_size,
273
+ 1,
274
+ dilation=1,
275
+ padding=get_padding(kernel_size, 1),
276
+ )
277
+ ),
278
+ weight_norm(
279
+ Conv1d(
280
+ channels,
281
+ channels,
282
+ kernel_size,
283
+ 1,
284
+ dilation=1,
285
+ padding=get_padding(kernel_size, 1),
286
+ )
287
+ ),
288
+ ]
289
+ )
290
+ self.convs2.apply(init_weights)
291
+
292
+ def forward(self, x, x_mask=None):
293
+ for c1, c2 in zip(self.convs1, self.convs2):
294
+ xt = F.leaky_relu(x, LRELU_SLOPE)
295
+ if x_mask is not None:
296
+ xt = xt * x_mask
297
+ xt = c1(xt)
298
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
299
+ if x_mask is not None:
300
+ xt = xt * x_mask
301
+ xt = c2(xt)
302
+ x = xt + x
303
+ if x_mask is not None:
304
+ x = x * x_mask
305
+ return x
306
+
307
+ def remove_weight_norm(self):
308
+ for l in self.convs1:
309
+ remove_weight_norm(l)
310
+ for l in self.convs2:
311
+ remove_weight_norm(l)
312
+
313
+
314
+ class ResBlock2(torch.nn.Module):
315
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
316
+ super(ResBlock2, self).__init__()
317
+ self.convs = nn.ModuleList(
318
+ [
319
+ weight_norm(
320
+ Conv1d(
321
+ channels,
322
+ channels,
323
+ kernel_size,
324
+ 1,
325
+ dilation=dilation[0],
326
+ padding=get_padding(kernel_size, dilation[0]),
327
+ )
328
+ ),
329
+ weight_norm(
330
+ Conv1d(
331
+ channels,
332
+ channels,
333
+ kernel_size,
334
+ 1,
335
+ dilation=dilation[1],
336
+ padding=get_padding(kernel_size, dilation[1]),
337
+ )
338
+ ),
339
+ ]
340
+ )
341
+ self.convs.apply(init_weights)
342
+
343
+ def forward(self, x, x_mask=None):
344
+ for c in self.convs:
345
+ xt = F.leaky_relu(x, LRELU_SLOPE)
346
+ if x_mask is not None:
347
+ xt = xt * x_mask
348
+ xt = c(xt)
349
+ x = xt + x
350
+ if x_mask is not None:
351
+ x = x * x_mask
352
+ return x
353
+
354
+ def remove_weight_norm(self):
355
+ for l in self.convs:
356
+ remove_weight_norm(l)
357
+
358
+
359
+ class Log(nn.Module):
360
+ def forward(self, x, x_mask, reverse=False, **kwargs):
361
+ if not reverse:
362
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
363
+ logdet = torch.sum(-y, [1, 2])
364
+ return y, logdet
365
+ else:
366
+ x = torch.exp(x) * x_mask
367
+ return x
368
+
369
+
370
+ class Flip(nn.Module):
371
+ def forward(self, x, *args, reverse=False, **kwargs):
372
+ x = torch.flip(x, [1])
373
+ if not reverse:
374
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
375
+ return x, logdet
376
+ else:
377
+ return x
378
+
379
+
380
+ class ElementwiseAffine(nn.Module):
381
+ def __init__(self, channels):
382
+ super().__init__()
383
+ self.channels = channels
384
+ self.m = nn.Parameter(torch.zeros(channels, 1))
385
+ self.logs = nn.Parameter(torch.zeros(channels, 1))
386
+
387
+ def forward(self, x, x_mask, reverse=False, **kwargs):
388
+ if not reverse:
389
+ y = self.m + torch.exp(self.logs) * x
390
+ y = y * x_mask
391
+ logdet = torch.sum(self.logs * x_mask, [1, 2])
392
+ return y, logdet
393
+ else:
394
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
395
+ return x
396
+
397
+
398
+ class ResidualCouplingLayer(nn.Module):
399
+ def __init__(
400
+ self,
401
+ channels,
402
+ hidden_channels,
403
+ kernel_size,
404
+ dilation_rate,
405
+ n_layers,
406
+ p_dropout=0,
407
+ gin_channels=0,
408
+ mean_only=False,
409
+ ):
410
+ assert channels % 2 == 0, "channels should be divisible by 2"
411
+ super().__init__()
412
+ self.channels = channels
413
+ self.hidden_channels = hidden_channels
414
+ self.kernel_size = kernel_size
415
+ self.dilation_rate = dilation_rate
416
+ self.n_layers = n_layers
417
+ self.half_channels = channels // 2
418
+ self.mean_only = mean_only
419
+
420
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
421
+ self.enc = WN(
422
+ hidden_channels,
423
+ kernel_size,
424
+ dilation_rate,
425
+ n_layers,
426
+ p_dropout=p_dropout,
427
+ gin_channels=gin_channels,
428
+ )
429
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
430
+ self.post.weight.data.zero_()
431
+ self.post.bias.data.zero_()
432
+
433
+ def forward(self, x, x_mask, g=None, reverse=False):
434
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
435
+ h = self.pre(x0) * x_mask
436
+ h = self.enc(h, x_mask, g=g)
437
+ stats = self.post(h) * x_mask
438
+ if not self.mean_only:
439
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
440
+ else:
441
+ m = stats
442
+ logs = torch.zeros_like(m)
443
+
444
+ if not reverse:
445
+ x1 = m + x1 * torch.exp(logs) * x_mask
446
+ x = torch.cat([x0, x1], 1)
447
+ logdet = torch.sum(logs, [1, 2])
448
+ return x, logdet
449
+ else:
450
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
451
+ x = torch.cat([x0, x1], 1)
452
+ return x
453
+
454
+
455
+ class ConvFlow(nn.Module):
456
+ def __init__(
457
+ self,
458
+ in_channels,
459
+ filter_channels,
460
+ kernel_size,
461
+ n_layers,
462
+ num_bins=10,
463
+ tail_bound=5.0,
464
+ ):
465
+ super().__init__()
466
+ self.in_channels = in_channels
467
+ self.filter_channels = filter_channels
468
+ self.kernel_size = kernel_size
469
+ self.n_layers = n_layers
470
+ self.num_bins = num_bins
471
+ self.tail_bound = tail_bound
472
+ self.half_channels = in_channels // 2
473
+
474
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
475
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
476
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
477
+ self.proj.weight.data.zero_()
478
+ self.proj.bias.data.zero_()
479
+
480
+ def forward(self, x, x_mask, g=None, reverse=False):
481
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
482
+ h = self.pre(x0)
483
+ h = self.convs(h, x_mask, g=g)
484
+ h = self.proj(h) * x_mask
485
+
486
+ b, c, t = x0.shape
487
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
488
+
489
+ unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
490
+ unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(self.filter_channels)
491
+ unnormalized_derivatives = h[..., 2 * self.num_bins :]
492
+
493
+ x1, logabsdet = piecewise_rational_quadratic_transform(
494
+ x1,
495
+ unnormalized_widths,
496
+ unnormalized_heights,
497
+ unnormalized_derivatives,
498
+ inverse=reverse,
499
+ tails="linear",
500
+ tail_bound=self.tail_bound,
501
+ )
502
+
503
+ x = torch.cat([x0, x1], 1) * x_mask
504
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
505
+ if not reverse:
506
+ return x, logdet
507
+ else:
508
+ return x
509
+
510
+
511
+ class LinearNorm(nn.Module):
512
+ def __init__(
513
+ self,
514
+ in_channels,
515
+ out_channels,
516
+ bias=True,
517
+ spectral_norm=False,
518
+ ):
519
+ super(LinearNorm, self).__init__()
520
+ self.fc = nn.Linear(in_channels, out_channels, bias)
521
+
522
+ if spectral_norm:
523
+ self.fc = nn.utils.spectral_norm(self.fc)
524
+
525
+ def forward(self, input):
526
+ out = self.fc(input)
527
+ return out
528
+
529
+
530
+ class Mish(nn.Module):
531
+ def __init__(self):
532
+ super(Mish, self).__init__()
533
+
534
+ def forward(self, x):
535
+ return x * torch.tanh(F.softplus(x))
536
+
537
+
538
+ class Conv1dGLU(nn.Module):
539
+ """
540
+ Conv1d + GLU(Gated Linear Unit) with residual connection.
541
+ For GLU refer to https://arxiv.org/abs/1612.08083 paper.
542
+ """
543
+
544
+ def __init__(self, in_channels, out_channels, kernel_size, dropout):
545
+ super(Conv1dGLU, self).__init__()
546
+ self.out_channels = out_channels
547
+ self.conv1 = ConvNorm(in_channels, 2 * out_channels, kernel_size=kernel_size)
548
+ self.dropout = nn.Dropout(dropout)
549
+
550
+ def forward(self, x):
551
+ residual = x
552
+ x = self.conv1(x)
553
+ x1, x2 = torch.split(x, split_size_or_sections=self.out_channels, dim=1)
554
+ x = x1 * torch.sigmoid(x2)
555
+ x = residual + self.dropout(x)
556
+ return x
557
+
558
+
559
+ class ConvNorm(nn.Module):
560
+ def __init__(
561
+ self,
562
+ in_channels,
563
+ out_channels,
564
+ kernel_size=1,
565
+ stride=1,
566
+ padding=None,
567
+ dilation=1,
568
+ bias=True,
569
+ spectral_norm=False,
570
+ ):
571
+ super(ConvNorm, self).__init__()
572
+
573
+ if padding is None:
574
+ assert kernel_size % 2 == 1
575
+ padding = int(dilation * (kernel_size - 1) / 2)
576
+
577
+ self.conv = torch.nn.Conv1d(
578
+ in_channels,
579
+ out_channels,
580
+ kernel_size=kernel_size,
581
+ stride=stride,
582
+ padding=padding,
583
+ dilation=dilation,
584
+ bias=bias,
585
+ )
586
+
587
+ if spectral_norm:
588
+ self.conv = nn.utils.spectral_norm(self.conv)
589
+
590
+ def forward(self, input):
591
+ out = self.conv(input)
592
+ return out
593
+
594
+
595
+ class MultiHeadAttention(nn.Module):
596
+ """Multi-Head Attention module"""
597
+
598
+ def __init__(self, n_head, d_model, d_k, d_v, dropout=0.0, spectral_norm=False):
599
+ super().__init__()
600
+
601
+ self.n_head = n_head
602
+ self.d_k = d_k
603
+ self.d_v = d_v
604
+
605
+ self.w_qs = nn.Linear(d_model, n_head * d_k)
606
+ self.w_ks = nn.Linear(d_model, n_head * d_k)
607
+ self.w_vs = nn.Linear(d_model, n_head * d_v)
608
+
609
+ self.attention = ScaledDotProductAttention(temperature=np.power(d_model, 0.5), dropout=dropout)
610
+
611
+ self.fc = nn.Linear(n_head * d_v, d_model)
612
+ self.dropout = nn.Dropout(dropout)
613
+
614
+ if spectral_norm:
615
+ self.w_qs = nn.utils.spectral_norm(self.w_qs)
616
+ self.w_ks = nn.utils.spectral_norm(self.w_ks)
617
+ self.w_vs = nn.utils.spectral_norm(self.w_vs)
618
+ self.fc = nn.utils.spectral_norm(self.fc)
619
+
620
+ def forward(self, x, mask=None):
621
+ d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
622
+ sz_b, len_x, _ = x.size()
623
+
624
+ residual = x
625
+
626
+ q = self.w_qs(x).view(sz_b, len_x, n_head, d_k)
627
+ k = self.w_ks(x).view(sz_b, len_x, n_head, d_k)
628
+ v = self.w_vs(x).view(sz_b, len_x, n_head, d_v)
629
+ q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k) # (n*b) x lq x dk
630
+ k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k) # (n*b) x lk x dk
631
+ v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_v) # (n*b) x lv x dv
632
+
633
+ if mask is not None:
634
+ slf_mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..
635
+ else:
636
+ slf_mask = None
637
+ output, attn = self.attention(q, k, v, mask=slf_mask)
638
+
639
+ output = output.view(n_head, sz_b, len_x, d_v)
640
+ output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_x, -1) # b x lq x (n*dv)
641
+
642
+ output = self.fc(output)
643
+
644
+ output = self.dropout(output) + residual
645
+ return output, attn
646
+
647
+
648
+ class ScaledDotProductAttention(nn.Module):
649
+ """Scaled Dot-Product Attention"""
650
+
651
+ def __init__(self, temperature, dropout):
652
+ super().__init__()
653
+ self.temperature = temperature
654
+ self.softmax = nn.Softmax(dim=2)
655
+ self.dropout = nn.Dropout(dropout)
656
+
657
+ def forward(self, q, k, v, mask=None):
658
+ attn = torch.bmm(q, k.transpose(1, 2))
659
+ attn = attn / self.temperature
660
+
661
+ if mask is not None:
662
+ attn = attn.masked_fill(mask, -np.inf)
663
+
664
+ attn = self.softmax(attn)
665
+ p_attn = self.dropout(attn)
666
+
667
+ output = torch.bmm(p_attn, v)
668
+ return output, attn
669
+
670
+
671
+ class MelStyleEncoder(nn.Module):
672
+ """MelStyleEncoder"""
673
+
674
+ def __init__(
675
+ self,
676
+ n_mel_channels=80,
677
+ style_hidden=128,
678
+ style_vector_dim=256,
679
+ style_kernel_size=5,
680
+ style_head=2,
681
+ dropout=0.1,
682
+ ):
683
+ super(MelStyleEncoder, self).__init__()
684
+ self.in_dim = n_mel_channels
685
+ self.hidden_dim = style_hidden
686
+ self.out_dim = style_vector_dim
687
+ self.kernel_size = style_kernel_size
688
+ self.n_head = style_head
689
+ self.dropout = dropout
690
+
691
+ self.spectral = nn.Sequential(
692
+ LinearNorm(self.in_dim, self.hidden_dim),
693
+ Mish(),
694
+ nn.Dropout(self.dropout),
695
+ LinearNorm(self.hidden_dim, self.hidden_dim),
696
+ Mish(),
697
+ nn.Dropout(self.dropout),
698
+ )
699
+
700
+ self.temporal = nn.Sequential(
701
+ Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
702
+ Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
703
+ )
704
+
705
+ self.slf_attn = MultiHeadAttention(
706
+ self.n_head,
707
+ self.hidden_dim,
708
+ self.hidden_dim // self.n_head,
709
+ self.hidden_dim // self.n_head,
710
+ self.dropout,
711
+ )
712
+
713
+ self.fc = LinearNorm(self.hidden_dim, self.out_dim)
714
+
715
+ def temporal_avg_pool(self, x, mask=None):
716
+ if mask is None:
717
+ out = torch.mean(x, dim=1)
718
+ else:
719
+ len_ = (~mask).sum(dim=1).unsqueeze(1)
720
+ x = x.masked_fill(mask.unsqueeze(-1), 0)
721
+ x = x.sum(dim=1)
722
+ out = torch.div(x, len_)
723
+ return out
724
+
725
+ def forward(self, x, mask=None):
726
+ x = x.transpose(1, 2)
727
+ if mask is not None:
728
+ mask = (mask.int() == 0).squeeze(1)
729
+ max_len = x.shape[1]
730
+ slf_attn_mask = mask.unsqueeze(1).expand(-1, max_len, -1) if mask is not None else None
731
+
732
+ # spectral
733
+ x = self.spectral(x)
734
+ # temporal
735
+ x = x.transpose(1, 2)
736
+ x = self.temporal(x)
737
+ x = x.transpose(1, 2)
738
+ # self-attention
739
+ if mask is not None:
740
+ x = x.masked_fill(mask.unsqueeze(-1), 0)
741
+ x, _ = self.slf_attn(x, mask=slf_attn_mask)
742
+ # fc
743
+ x = self.fc(x)
744
+ # temoral average pooling
745
+ w = self.temporal_avg_pool(x, mask=mask)
746
+
747
+ return w.unsqueeze(-1)
748
+
749
+
750
+ class MelStyleEncoderVAE(nn.Module):
751
+ def __init__(self, spec_channels, z_latent_dim, emb_dim):
752
+ super().__init__()
753
+ self.ref_encoder = MelStyleEncoder(spec_channels, style_vector_dim=emb_dim)
754
+ self.fc1 = nn.Linear(emb_dim, z_latent_dim)
755
+ self.fc2 = nn.Linear(emb_dim, z_latent_dim)
756
+ self.fc3 = nn.Linear(z_latent_dim, emb_dim)
757
+ self.z_latent_dim = z_latent_dim
758
+
759
+ def reparameterize(self, mu, logvar):
760
+ if self.training:
761
+ std = torch.exp(0.5 * logvar)
762
+ eps = torch.randn_like(std)
763
+ return eps.mul(std).add_(mu)
764
+ else:
765
+ return mu
766
+
767
+ def forward(self, inputs, mask=None):
768
+ enc_out = self.ref_encoder(inputs.squeeze(-1), mask).squeeze(-1)
769
+ mu = self.fc1(enc_out)
770
+ logvar = self.fc2(enc_out)
771
+ posterior = D.Normal(mu, torch.exp(logvar))
772
+ kl_divergence = D.kl_divergence(posterior, D.Normal(torch.zeros_like(mu), torch.ones_like(logvar)))
773
+ loss_kl = kl_divergence.mean()
774
+
775
+ z = posterior.rsample()
776
+ style_embed = self.fc3(z)
777
+
778
+ return style_embed.unsqueeze(-1), loss_kl
779
+
780
+ def infer(self, inputs=None, random_sample=False, manual_latent=None):
781
+ if manual_latent is None:
782
+ if random_sample:
783
+ dev = next(self.parameters()).device
784
+ posterior = D.Normal(
785
+ torch.zeros(1, self.z_latent_dim, device=dev),
786
+ torch.ones(1, self.z_latent_dim, device=dev),
787
+ )
788
+ z = posterior.rsample()
789
+ else:
790
+ enc_out = self.ref_encoder(inputs.transpose(1, 2))
791
+ mu = self.fc1(enc_out)
792
+ z = mu
793
+ else:
794
+ z = manual_latent
795
+ style_embed = self.fc3(z)
796
+ return style_embed.unsqueeze(-1), z
797
+
798
+
799
+ class ActNorm(nn.Module):
800
+ def __init__(self, channels, ddi=False, **kwargs):
801
+ super().__init__()
802
+ self.channels = channels
803
+ self.initialized = not ddi
804
+
805
+ self.logs = nn.Parameter(torch.zeros(1, channels, 1))
806
+ self.bias = nn.Parameter(torch.zeros(1, channels, 1))
807
+
808
+ def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):
809
+ if x_mask is None:
810
+ x_mask = torch.ones(x.size(0), 1, x.size(2)).to(device=x.device, dtype=x.dtype)
811
+ x_len = torch.sum(x_mask, [1, 2])
812
+ if not self.initialized:
813
+ self.initialize(x, x_mask)
814
+ self.initialized = True
815
+
816
+ if reverse:
817
+ z = (x - self.bias) * torch.exp(-self.logs) * x_mask
818
+ logdet = None
819
+ return z
820
+ else:
821
+ z = (self.bias + torch.exp(self.logs) * x) * x_mask
822
+ logdet = torch.sum(self.logs) * x_len # [b]
823
+ return z, logdet
824
+
825
+ def store_inverse(self):
826
+ pass
827
+
828
+ def set_ddi(self, ddi):
829
+ self.initialized = not ddi
830
+
831
+ def initialize(self, x, x_mask):
832
+ with torch.no_grad():
833
+ denom = torch.sum(x_mask, [0, 2])
834
+ m = torch.sum(x * x_mask, [0, 2]) / denom
835
+ m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom
836
+ v = m_sq - (m**2)
837
+ logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6))
838
+
839
+ bias_init = (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype)
840
+ logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype)
841
+
842
+ self.bias.data.copy_(bias_init)
843
+ self.logs.data.copy_(logs_init)
844
+
845
+
846
+ class InvConvNear(nn.Module):
847
+ def __init__(self, channels, n_split=4, no_jacobian=False, **kwargs):
848
+ super().__init__()
849
+ assert n_split % 2 == 0
850
+ self.channels = channels
851
+ self.n_split = n_split
852
+ self.no_jacobian = no_jacobian
853
+
854
+ w_init = torch.linalg.qr(torch.FloatTensor(self.n_split, self.n_split).normal_())[0]
855
+ if torch.det(w_init) < 0:
856
+ w_init[:, 0] = -1 * w_init[:, 0]
857
+ self.weight = nn.Parameter(w_init)
858
+
859
+ def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):
860
+ b, c, t = x.size()
861
+ assert c % self.n_split == 0
862
+ if x_mask is None:
863
+ x_mask = 1
864
+ x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t
865
+ else:
866
+ x_len = torch.sum(x_mask, [1, 2])
867
+
868
+ x = x.view(b, 2, c // self.n_split, self.n_split // 2, t)
869
+ x = x.permute(0, 1, 3, 2, 4).contiguous().view(b, self.n_split, c // self.n_split, t)
870
+
871
+ if reverse:
872
+ if hasattr(self, "weight_inv"):
873
+ weight = self.weight_inv
874
+ else:
875
+ weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)
876
+ logdet = None
877
+ else:
878
+ weight = self.weight
879
+ if self.no_jacobian:
880
+ logdet = 0
881
+ else:
882
+ logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len # [b]
883
+
884
+ weight = weight.view(self.n_split, self.n_split, 1, 1)
885
+ z = F.conv2d(x, weight)
886
+
887
+ z = z.view(b, 2, self.n_split // 2, c // self.n_split, t)
888
+ z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask
889
+ if reverse:
890
+ return z
891
+ else:
892
+ return z, logdet
893
+
894
+ def store_inverse(self):
895
+ self.weight_inv = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)
GPT_SoVITS/module/mrte_model.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ class MRTE(nn.Module):
10
+ def __init__(
11
+ self,
12
+ content_enc_channels=192,
13
+ hidden_size=512,
14
+ out_channels=192,
15
+ kernel_size=5,
16
+ n_heads=4,
17
+ ge_layer=2,
18
+ ):
19
+ super(MRTE, self).__init__()
20
+ self.cross_attention = MultiHeadAttention(hidden_size, hidden_size, n_heads)
21
+ self.c_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
22
+ self.text_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
23
+ self.c_post = nn.Conv1d(hidden_size, out_channels, 1)
24
+
25
+ def forward(self, ssl_enc, ssl_mask, text, text_mask, ge, test=None):
26
+ if ge == None:
27
+ ge = 0
28
+ attn_mask = text_mask.unsqueeze(2) * ssl_mask.unsqueeze(-1)
29
+
30
+ ssl_enc = self.c_pre(ssl_enc * ssl_mask)
31
+ text_enc = self.text_pre(text * text_mask)
32
+ if test != None:
33
+ if test == 0:
34
+ x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
35
+ elif test == 1:
36
+ x = ssl_enc + ge
37
+ elif test == 2:
38
+ x = self.cross_attention(ssl_enc * 0 * ssl_mask, text_enc * text_mask, attn_mask) + ge
39
+ else:
40
+ raise ValueError("test should be 0,1,2")
41
+ else:
42
+ x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
43
+ x = self.c_post(x * ssl_mask)
44
+ return x
45
+
46
+
47
+ class SpeakerEncoder(torch.nn.Module):
48
+ def __init__(
49
+ self,
50
+ mel_n_channels=80,
51
+ model_num_layers=2,
52
+ model_hidden_size=256,
53
+ model_embedding_size=256,
54
+ ):
55
+ super(SpeakerEncoder, self).__init__()
56
+ self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True)
57
+ self.linear = nn.Linear(model_hidden_size, model_embedding_size)
58
+ self.relu = nn.ReLU()
59
+
60
+ def forward(self, mels):
61
+ self.lstm.flatten_parameters()
62
+ _, (hidden, _) = self.lstm(mels.transpose(-1, -2))
63
+ embeds_raw = self.relu(self.linear(hidden[-1]))
64
+ return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)
65
+
66
+
67
+ class MELEncoder(nn.Module):
68
+ def __init__(
69
+ self,
70
+ in_channels,
71
+ out_channels,
72
+ hidden_channels,
73
+ kernel_size,
74
+ dilation_rate,
75
+ n_layers,
76
+ ):
77
+ super().__init__()
78
+ self.in_channels = in_channels
79
+ self.out_channels = out_channels
80
+ self.hidden_channels = hidden_channels
81
+ self.kernel_size = kernel_size
82
+ self.dilation_rate = dilation_rate
83
+ self.n_layers = n_layers
84
+
85
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
86
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers)
87
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
88
+
89
+ def forward(self, x):
90
+ # print(x.shape,x_lengths.shape)
91
+ x = self.pre(x)
92
+ x = self.enc(x)
93
+ x = self.proj(x)
94
+ return x
95
+
96
+
97
+ class WN(torch.nn.Module):
98
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers):
99
+ super(WN, self).__init__()
100
+ assert kernel_size % 2 == 1
101
+ self.hidden_channels = hidden_channels
102
+ self.kernel_size = kernel_size
103
+ self.dilation_rate = dilation_rate
104
+ self.n_layers = n_layers
105
+
106
+ self.in_layers = torch.nn.ModuleList()
107
+ self.res_skip_layers = torch.nn.ModuleList()
108
+
109
+ for i in range(n_layers):
110
+ dilation = dilation_rate**i
111
+ padding = int((kernel_size * dilation - dilation) / 2)
112
+ in_layer = nn.Conv1d(
113
+ hidden_channels,
114
+ 2 * hidden_channels,
115
+ kernel_size,
116
+ dilation=dilation,
117
+ padding=padding,
118
+ )
119
+ in_layer = weight_norm(in_layer)
120
+ self.in_layers.append(in_layer)
121
+
122
+ # last one is not necessary
123
+ if i < n_layers - 1:
124
+ res_skip_channels = 2 * hidden_channels
125
+ else:
126
+ res_skip_channels = hidden_channels
127
+
128
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
129
+ res_skip_layer = weight_norm(res_skip_layer, name="weight")
130
+ self.res_skip_layers.append(res_skip_layer)
131
+
132
+ def forward(self, x):
133
+ output = torch.zeros_like(x)
134
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
135
+
136
+ for i in range(self.n_layers):
137
+ x_in = self.in_layers[i](x)
138
+
139
+ acts = fused_add_tanh_sigmoid_multiply(x_in, n_channels_tensor)
140
+
141
+ res_skip_acts = self.res_skip_layers[i](acts)
142
+ if i < self.n_layers - 1:
143
+ res_acts = res_skip_acts[:, : self.hidden_channels, :]
144
+ x = x + res_acts
145
+ output = output + res_skip_acts[:, self.hidden_channels :, :]
146
+ else:
147
+ output = output + res_skip_acts
148
+ return output
149
+
150
+ def remove_weight_norm(self):
151
+ for l in self.in_layers:
152
+ remove_weight_norm(l)
153
+ for l in self.res_skip_layers:
154
+ remove_weight_norm(l)
155
+
156
+
157
+ @torch.jit.script
158
+ def fused_add_tanh_sigmoid_multiply(input, n_channels):
159
+ n_channels_int = n_channels[0]
160
+ t_act = torch.tanh(input[:, :n_channels_int, :])
161
+ s_act = torch.sigmoid(input[:, n_channels_int:, :])
162
+ acts = t_act * s_act
163
+ return acts
164
+
165
+
166
+ if __name__ == "__main__":
167
+ content_enc = torch.randn(3, 192, 100)
168
+ content_mask = torch.ones(3, 1, 100)
169
+ ref_mel = torch.randn(3, 128, 30)
170
+ ref_mask = torch.ones(3, 1, 30)
171
+ model = MRTE()
172
+ out = model(content_enc, content_mask, ref_mel, ref_mask)
173
+ print(out.shape)
GPT_SoVITS/module/quantize.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing as tp
11
+
12
+ import torch
13
+ from torch import nn
14
+
15
+ from module.core_vq import ResidualVectorQuantization
16
+
17
+
18
+ @dataclass
19
+ class QuantizedResult:
20
+ quantized: torch.Tensor
21
+ codes: torch.Tensor
22
+ bandwidth: torch.Tensor # bandwidth in kb/s used, per batch item.
23
+ penalty: tp.Optional[torch.Tensor] = None
24
+ metrics: dict = field(default_factory=dict)
25
+
26
+
27
+ class ResidualVectorQuantizer(nn.Module):
28
+ """Residual Vector Quantizer.
29
+ Args:
30
+ dimension (int): Dimension of the codebooks.
31
+ n_q (int): Number of residual vector quantizers used.
32
+ bins (int): Codebook size.
33
+ decay (float): Decay for exponential moving average over the codebooks.
34
+ kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
35
+ kmeans_iters (int): Number of iterations used for kmeans initialization.
36
+ threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
37
+ that have an exponential moving average cluster size less than the specified threshold with
38
+ randomly selected vector from the current batch.
39
+ """
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(
70
+ self,
71
+ x: torch.Tensor,
72
+ n_q: tp.Optional[int] = None,
73
+ layers: tp.Optional[list] = None,
74
+ ) -> QuantizedResult:
75
+ """Residual vector quantization on the given input tensor.
76
+ Args:
77
+ x (torch.Tensor): Input tensor.
78
+ n_q (int): Number of quantizer used to quantize. Default: All quantizers.
79
+ layers (list): Layer that need to return quantized. Defalt: None.
80
+ Returns:
81
+ QuantizedResult:
82
+ The quantized (or approximately quantized) representation with
83
+ the associated numbert quantizers and layer quantized required to return.
84
+ """
85
+ n_q = n_q if n_q else self.n_q
86
+ if layers and max(layers) >= n_q:
87
+ raise ValueError(
88
+ f"Last layer index in layers: A {max(layers)}. Number of quantizers in RVQ: B {self.n_q}. A must less than B."
89
+ )
90
+ quantized, codes, commit_loss, quantized_list = self.vq(x, n_q=n_q, layers=layers)
91
+ return quantized, codes, torch.mean(commit_loss), quantized_list
92
+
93
+ def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None, st: tp.Optional[int] = None) -> torch.Tensor:
94
+ """Encode a given input tensor with the specified sample rate at the given bandwidth.
95
+ The RVQ encode method sets the appropriate number of quantizer to use
96
+ and returns indices for each quantizer.
97
+ Args:
98
+ x (torch.Tensor): Input tensor.
99
+ n_q (int): Number of quantizer used to quantize. Default: All quantizers.
100
+ st (int): Start to encode input from which layers. Default: 0.
101
+ """
102
+ n_q = n_q if n_q else self.n_q
103
+ st = st or 0
104
+ codes = self.vq.encode(x, n_q=n_q, st=st)
105
+ return codes
106
+
107
+ def decode(self, codes: torch.Tensor, st: int = 0) -> torch.Tensor:
108
+ """Decode the given codes to the quantized representation.
109
+ Args:
110
+ codes (torch.Tensor): Input indices for each quantizer.
111
+ st (int): Start to decode input codes from which layers. Default: 0.
112
+ """
113
+ quantized = self.vq.decode(codes, st=st)
114
+ return quantized
GPT_SoVITS/module/transforms.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
13
+ inputs,
14
+ unnormalized_widths,
15
+ unnormalized_heights,
16
+ unnormalized_derivatives,
17
+ inverse=False,
18
+ tails=None,
19
+ tail_bound=1.0,
20
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
21
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
22
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
23
+ ):
24
+ if tails is None:
25
+ spline_fn = rational_quadratic_spline
26
+ spline_kwargs = {}
27
+ else:
28
+ spline_fn = unconstrained_rational_quadratic_spline
29
+ spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
30
+
31
+ outputs, logabsdet = spline_fn(
32
+ inputs=inputs,
33
+ unnormalized_widths=unnormalized_widths,
34
+ unnormalized_heights=unnormalized_heights,
35
+ unnormalized_derivatives=unnormalized_derivatives,
36
+ inverse=inverse,
37
+ min_bin_width=min_bin_width,
38
+ min_bin_height=min_bin_height,
39
+ min_derivative=min_derivative,
40
+ **spline_kwargs,
41
+ )
42
+ return outputs, logabsdet
43
+
44
+
45
+ def searchsorted(bin_locations, inputs, eps=1e-6):
46
+ bin_locations[..., -1] += eps
47
+ return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
48
+
49
+
50
+ def unconstrained_rational_quadratic_spline(
51
+ inputs,
52
+ unnormalized_widths,
53
+ unnormalized_heights,
54
+ unnormalized_derivatives,
55
+ inverse=False,
56
+ tails="linear",
57
+ tail_bound=1.0,
58
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
59
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
60
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
61
+ ):
62
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
63
+ outside_interval_mask = ~inside_interval_mask
64
+
65
+ outputs = torch.zeros_like(inputs)
66
+ logabsdet = torch.zeros_like(inputs)
67
+
68
+ if tails == "linear":
69
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
70
+ constant = np.log(np.exp(1 - min_derivative) - 1)
71
+ unnormalized_derivatives[..., 0] = constant
72
+ unnormalized_derivatives[..., -1] = constant
73
+
74
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
75
+ logabsdet[outside_interval_mask] = 0
76
+ else:
77
+ raise RuntimeError("{} tails are not implemented.".format(tails))
78
+
79
+ (
80
+ outputs[inside_interval_mask],
81
+ logabsdet[inside_interval_mask],
82
+ ) = 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,
89
+ right=tail_bound,
90
+ bottom=-tail_bound,
91
+ top=tail_bound,
92
+ min_bin_width=min_bin_width,
93
+ min_bin_height=min_bin_height,
94
+ min_derivative=min_derivative,
95
+ )
96
+
97
+ return outputs, logabsdet
98
+
99
+
100
+ def rational_quadratic_spline(
101
+ inputs,
102
+ unnormalized_widths,
103
+ unnormalized_heights,
104
+ unnormalized_derivatives,
105
+ inverse=False,
106
+ left=0.0,
107
+ right=1.0,
108
+ bottom=0.0,
109
+ top=1.0,
110
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
111
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
112
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
113
+ ):
114
+ if torch.min(inputs) < left or torch.max(inputs) > right:
115
+ raise ValueError("Input to a transform is not within its domain")
116
+
117
+ num_bins = unnormalized_widths.shape[-1]
118
+
119
+ if min_bin_width * num_bins > 1.0:
120
+ raise ValueError("Minimal bin width too large for the number of bins")
121
+ if min_bin_height * num_bins > 1.0:
122
+ raise ValueError("Minimal bin height too large for the number of bins")
123
+
124
+ widths = F.softmax(unnormalized_widths, dim=-1)
125
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
126
+ cumwidths = torch.cumsum(widths, dim=-1)
127
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
128
+ cumwidths = (right - left) * cumwidths + left
129
+ cumwidths[..., 0] = left
130
+ cumwidths[..., -1] = right
131
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
132
+
133
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
134
+
135
+ heights = F.softmax(unnormalized_heights, dim=-1)
136
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
137
+ cumheights = torch.cumsum(heights, dim=-1)
138
+ cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
139
+ cumheights = (top - bottom) * cumheights + bottom
140
+ cumheights[..., 0] = bottom
141
+ cumheights[..., -1] = top
142
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
143
+
144
+ if inverse:
145
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
146
+ else:
147
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
148
+
149
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
150
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
151
+
152
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
153
+ delta = heights / widths
154
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
155
+
156
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
157
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
158
+
159
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
160
+
161
+ if inverse:
162
+ a = (inputs - input_cumheights) * (
163
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
164
+ ) + input_heights * (input_delta - input_derivatives)
165
+ b = input_heights * input_derivatives - (inputs - input_cumheights) * (
166
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
167
+ )
168
+ c = -input_delta * (inputs - input_cumheights)
169
+
170
+ discriminant = b.pow(2) - 4 * a * c
171
+ assert (discriminant >= 0).all()
172
+
173
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
174
+ outputs = root * input_bin_widths + input_cumwidths
175
+
176
+ theta_one_minus_theta = root * (1 - root)
177
+ denominator = input_delta + (
178
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta) * theta_one_minus_theta
179
+ )
180
+ derivative_numerator = input_delta.pow(2) * (
181
+ input_derivatives_plus_one * root.pow(2)
182
+ + 2 * input_delta * theta_one_minus_theta
183
+ + input_derivatives * (1 - root).pow(2)
184
+ )
185
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
186
+
187
+ return outputs, -logabsdet
188
+ else:
189
+ theta = (inputs - input_cumwidths) / input_bin_widths
190
+ theta_one_minus_theta = theta * (1 - theta)
191
+
192
+ numerator = input_heights * (input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta)
193
+ denominator = input_delta + (
194
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta) * theta_one_minus_theta
195
+ )
196
+ outputs = input_cumheights + numerator / denominator
197
+
198
+ derivative_numerator = input_delta.pow(2) * (
199
+ input_derivatives_plus_one * theta.pow(2)
200
+ + 2 * input_delta * theta_one_minus_theta
201
+ + input_derivatives * (1 - theta).pow(2)
202
+ )
203
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
204
+
205
+ return outputs, logabsdet
GPT_SoVITS/prepare_datasets/1-get-text.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ inp_text = os.environ.get("inp_text")
6
+ inp_wav_dir = os.environ.get("inp_wav_dir")
7
+ exp_name = os.environ.get("exp_name")
8
+ i_part = os.environ.get("i_part")
9
+ all_parts = os.environ.get("all_parts")
10
+ if "_CUDA_VISIBLE_DEVICES" in os.environ:
11
+ os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
12
+ opt_dir = os.environ.get("opt_dir")
13
+ bert_pretrained_dir = os.environ.get("bert_pretrained_dir")
14
+ import torch
15
+
16
+ is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
17
+ version = os.environ.get("version", None)
18
+ import traceback
19
+ import os.path
20
+ from text.cleaner import clean_text
21
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
22
+ from tools.my_utils import clean_path
23
+
24
+ # inp_text=sys.argv[1]
25
+ # inp_wav_dir=sys.argv[2]
26
+ # exp_name=sys.argv[3]
27
+ # i_part=sys.argv[4]
28
+ # all_parts=sys.argv[5]
29
+ # os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[6]#i_gpu
30
+ # opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
31
+ # bert_pretrained_dir="/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large"
32
+
33
+ from time import time as ttime
34
+ import shutil
35
+
36
+
37
+ def my_save(fea, path): #####fix issue: torch.save doesn't support chinese path
38
+ dir = os.path.dirname(path)
39
+ name = os.path.basename(path)
40
+ # tmp_path="%s/%s%s.pth"%(dir,ttime(),i_part)
41
+ tmp_path = "%s%s.pth" % (ttime(), i_part)
42
+ torch.save(fea, tmp_path)
43
+ shutil.move(tmp_path, "%s/%s" % (dir, name))
44
+
45
+
46
+ txt_path = "%s/2-name2text-%s.txt" % (opt_dir, i_part)
47
+ if os.path.exists(txt_path) == False:
48
+ bert_dir = "%s/3-bert" % (opt_dir)
49
+ os.makedirs(opt_dir, exist_ok=True)
50
+ os.makedirs(bert_dir, exist_ok=True)
51
+ if torch.cuda.is_available():
52
+ device = "cuda:0"
53
+ # elif torch.backends.mps.is_available():
54
+ # device = "mps"
55
+ else:
56
+ device = "cpu"
57
+ if os.path.exists(bert_pretrained_dir):
58
+ ...
59
+ else:
60
+ raise FileNotFoundError(bert_pretrained_dir)
61
+ tokenizer = AutoTokenizer.from_pretrained(bert_pretrained_dir)
62
+ bert_model = AutoModelForMaskedLM.from_pretrained(bert_pretrained_dir)
63
+ if is_half == True:
64
+ bert_model = bert_model.half().to(device)
65
+ else:
66
+ bert_model = bert_model.to(device)
67
+
68
+ def get_bert_feature(text, word2ph):
69
+ with torch.no_grad():
70
+ inputs = tokenizer(text, return_tensors="pt")
71
+ for i in inputs:
72
+ inputs[i] = inputs[i].to(device)
73
+ res = bert_model(**inputs, output_hidden_states=True)
74
+ res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
75
+
76
+ assert len(word2ph) == len(text)
77
+ phone_level_feature = []
78
+ for i in range(len(word2ph)):
79
+ repeat_feature = res[i].repeat(word2ph[i], 1)
80
+ phone_level_feature.append(repeat_feature)
81
+
82
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
83
+
84
+ return phone_level_feature.T
85
+
86
+ def process(data, res):
87
+ for name, text, lan in data:
88
+ try:
89
+ name = clean_path(name)
90
+ name = os.path.basename(name)
91
+ print(name)
92
+ phones, word2ph, norm_text = clean_text(text.replace("%", "-").replace("¥", ","), lan, version)
93
+ path_bert = "%s/%s.pt" % (bert_dir, name)
94
+ if os.path.exists(path_bert) == False and lan == "zh":
95
+ bert_feature = get_bert_feature(norm_text, word2ph)
96
+ assert bert_feature.shape[-1] == len(phones)
97
+ # torch.save(bert_feature, path_bert)
98
+ my_save(bert_feature, path_bert)
99
+ phones = " ".join(phones)
100
+ # res.append([name,phones])
101
+ res.append([name, phones, word2ph, norm_text])
102
+ except:
103
+ print(name, text, traceback.format_exc())
104
+
105
+ todo = []
106
+ res = []
107
+ with open(inp_text, "r", encoding="utf8") as f:
108
+ lines = f.read().strip("\n").split("\n")
109
+
110
+ language_v1_to_language_v2 = {
111
+ "ZH": "zh",
112
+ "zh": "zh",
113
+ "JP": "ja",
114
+ "jp": "ja",
115
+ "JA": "ja",
116
+ "ja": "ja",
117
+ "EN": "en",
118
+ "en": "en",
119
+ "En": "en",
120
+ "KO": "ko",
121
+ "Ko": "ko",
122
+ "ko": "ko",
123
+ "yue": "yue",
124
+ "YUE": "yue",
125
+ "Yue": "yue",
126
+ }
127
+ for line in lines[int(i_part) :: int(all_parts)]:
128
+ try:
129
+ wav_name, spk_name, language, text = line.split("|")
130
+ # todo.append([name,text,"zh"])
131
+ if language in language_v1_to_language_v2.keys():
132
+ todo.append([wav_name, text, language_v1_to_language_v2.get(language, language)])
133
+ else:
134
+ print(f"\033[33m[Waring] The {language = } of {wav_name} is not supported for training.\033[0m")
135
+ except:
136
+ print(line, traceback.format_exc())
137
+
138
+ process(todo, res)
139
+ opt = []
140
+ for name, phones, word2ph, norm_text in res:
141
+ opt.append("%s\t%s\t%s\t%s" % (name, phones, word2ph, norm_text))
142
+ with open(txt_path, "w", encoding="utf8") as f:
143
+ f.write("\n".join(opt) + "\n")
GPT_SoVITS/prepare_datasets/2-get-hubert-wav32k.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import sys
4
+ import os
5
+
6
+ inp_text = os.environ.get("inp_text")
7
+ inp_wav_dir = os.environ.get("inp_wav_dir")
8
+ exp_name = os.environ.get("exp_name")
9
+ i_part = os.environ.get("i_part")
10
+ all_parts = os.environ.get("all_parts")
11
+ if "_CUDA_VISIBLE_DEVICES" in os.environ:
12
+ os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
13
+ from feature_extractor import cnhubert
14
+
15
+ opt_dir = os.environ.get("opt_dir")
16
+ cnhubert.cnhubert_base_path = os.environ.get("cnhubert_base_dir")
17
+ import torch
18
+
19
+ is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
20
+
21
+ import traceback
22
+ import numpy as np
23
+ from scipy.io import wavfile
24
+ import librosa
25
+
26
+ now_dir = os.getcwd()
27
+ sys.path.append(now_dir)
28
+ from tools.my_utils import load_audio, clean_path
29
+
30
+ # from config import cnhubert_base_path
31
+ # cnhubert.cnhubert_base_path=cnhubert_base_path
32
+ # inp_text=sys.argv[1]
33
+ # inp_wav_dir=sys.argv[2]
34
+ # exp_name=sys.argv[3]
35
+ # i_part=sys.argv[4]
36
+ # all_parts=sys.argv[5]
37
+ # os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[6]
38
+ # cnhubert.cnhubert_base_path=sys.argv[7]
39
+ # opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
40
+
41
+ from time import time as ttime
42
+ import shutil
43
+
44
+
45
+ def my_save(fea, path): #####fix issue: torch.save doesn't support chinese path
46
+ dir = os.path.dirname(path)
47
+ name = os.path.basename(path)
48
+ # tmp_path="%s/%s%s.pth"%(dir,ttime(),i_part)
49
+ tmp_path = "%s%s.pth" % (ttime(), i_part)
50
+ torch.save(fea, tmp_path)
51
+ shutil.move(tmp_path, "%s/%s" % (dir, name))
52
+
53
+
54
+ hubert_dir = "%s/4-cnhubert" % (opt_dir)
55
+ wav32dir = "%s/5-wav32k" % (opt_dir)
56
+ os.makedirs(opt_dir, exist_ok=True)
57
+ os.makedirs(hubert_dir, exist_ok=True)
58
+ os.makedirs(wav32dir, exist_ok=True)
59
+
60
+ maxx = 0.95
61
+ alpha = 0.5
62
+ if torch.cuda.is_available():
63
+ device = "cuda:0"
64
+ # elif torch.backends.mps.is_available():
65
+ # device = "mps"
66
+ else:
67
+ device = "cpu"
68
+ model = cnhubert.get_model()
69
+ # is_half=False
70
+ if is_half == True:
71
+ model = model.half().to(device)
72
+ else:
73
+ model = model.to(device)
74
+
75
+ nan_fails = []
76
+
77
+
78
+ def name2go(wav_name, wav_path):
79
+ hubert_path = "%s/%s.pt" % (hubert_dir, wav_name)
80
+ if os.path.exists(hubert_path):
81
+ return
82
+ tmp_audio = load_audio(wav_path, 32000)
83
+ tmp_max = np.abs(tmp_audio).max()
84
+ if tmp_max > 2.2:
85
+ print("%s-filtered,%s" % (wav_name, tmp_max))
86
+ return
87
+ tmp_audio32 = (tmp_audio / tmp_max * (maxx * alpha * 32768)) + ((1 - alpha) * 32768) * tmp_audio
88
+ tmp_audio32b = (tmp_audio / tmp_max * (maxx * alpha * 1145.14)) + ((1 - alpha) * 1145.14) * tmp_audio
89
+ tmp_audio = librosa.resample(tmp_audio32b, orig_sr=32000, target_sr=16000) # 不是重采样问题
90
+ tensor_wav16 = torch.from_numpy(tmp_audio)
91
+ if is_half == True:
92
+ tensor_wav16 = tensor_wav16.half().to(device)
93
+ else:
94
+ tensor_wav16 = tensor_wav16.to(device)
95
+ ssl = model.model(tensor_wav16.unsqueeze(0))["last_hidden_state"].transpose(1, 2).cpu() # torch.Size([1, 768, 215])
96
+ if np.isnan(ssl.detach().numpy()).sum() != 0:
97
+ nan_fails.append((wav_name, wav_path))
98
+ print("nan filtered:%s" % wav_name)
99
+ return
100
+ wavfile.write(
101
+ "%s/%s" % (wav32dir, wav_name),
102
+ 32000,
103
+ tmp_audio32.astype("int16"),
104
+ )
105
+ my_save(ssl, hubert_path)
106
+
107
+
108
+ with open(inp_text, "r", encoding="utf8") as f:
109
+ lines = f.read().strip("\n").split("\n")
110
+
111
+ for line in lines[int(i_part) :: int(all_parts)]:
112
+ try:
113
+ # wav_name,text=line.split("\t")
114
+ wav_name, spk_name, language, text = line.split("|")
115
+ wav_name = clean_path(wav_name)
116
+ if inp_wav_dir != "" and inp_wav_dir != None:
117
+ wav_name = os.path.basename(wav_name)
118
+ wav_path = "%s/%s" % (inp_wav_dir, wav_name)
119
+
120
+ else:
121
+ wav_path = wav_name
122
+ wav_name = os.path.basename(wav_name)
123
+ name2go(wav_name, wav_path)
124
+ except:
125
+ print(line, traceback.format_exc())
126
+
127
+ if len(nan_fails) > 0 and is_half == True:
128
+ is_half = False
129
+ model = model.float()
130
+ for wav in nan_fails:
131
+ try:
132
+ name2go(wav[0], wav[1])
133
+ except:
134
+ print(wav_name, traceback.format_exc())
GPT_SoVITS/prepare_datasets/3-get-semantic.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ inp_text = os.environ.get("inp_text")
4
+ exp_name = os.environ.get("exp_name")
5
+ i_part = os.environ.get("i_part")
6
+ all_parts = os.environ.get("all_parts")
7
+ if "_CUDA_VISIBLE_DEVICES" in os.environ:
8
+ os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
9
+ opt_dir = os.environ.get("opt_dir")
10
+ pretrained_s2G = os.environ.get("pretrained_s2G")
11
+ s2config_path = os.environ.get("s2config_path")
12
+
13
+ if os.path.exists(pretrained_s2G):
14
+ ...
15
+ else:
16
+ raise FileNotFoundError(pretrained_s2G)
17
+ # version=os.environ.get("version","v2")
18
+ size = os.path.getsize(pretrained_s2G)
19
+ if size < 82978 * 1024:
20
+ version = "v1"
21
+ elif size < 100 * 1024 * 1024:
22
+ version = "v2"
23
+ elif size < 103520 * 1024:
24
+ version = "v1"
25
+ elif size < 700 * 1024 * 1024:
26
+ version = "v2"
27
+ else:
28
+ version = "v3"
29
+ import torch
30
+
31
+ is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
32
+ import traceback
33
+ import sys
34
+
35
+ now_dir = os.getcwd()
36
+ sys.path.append(now_dir)
37
+ import logging
38
+ import utils
39
+
40
+ if version != "v3":
41
+ from module.models import SynthesizerTrn
42
+ else:
43
+ from module.models import SynthesizerTrnV3 as SynthesizerTrn
44
+ from tools.my_utils import clean_path
45
+
46
+ logging.getLogger("numba").setLevel(logging.WARNING)
47
+ # from config import pretrained_s2G
48
+
49
+ # inp_text=sys.argv[1]
50
+ # exp_name=sys.argv[2]
51
+ # i_part=sys.argv[3]
52
+ # all_parts=sys.argv[4]
53
+ # os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[5]
54
+ # opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
55
+
56
+
57
+ hubert_dir = "%s/4-cnhubert" % (opt_dir)
58
+ semantic_path = "%s/6-name2semantic-%s.tsv" % (opt_dir, i_part)
59
+ if os.path.exists(semantic_path) == False:
60
+ os.makedirs(opt_dir, exist_ok=True)
61
+
62
+ if torch.cuda.is_available():
63
+ device = "cuda"
64
+ # elif torch.backends.mps.is_available():
65
+ # device = "mps"
66
+ else:
67
+ device = "cpu"
68
+ hps = utils.get_hparams_from_file(s2config_path)
69
+ vq_model = SynthesizerTrn(
70
+ hps.data.filter_length // 2 + 1,
71
+ hps.train.segment_size // hps.data.hop_length,
72
+ n_speakers=hps.data.n_speakers,
73
+ version=version,
74
+ **hps.model,
75
+ )
76
+ if is_half == True:
77
+ vq_model = vq_model.half().to(device)
78
+ else:
79
+ vq_model = vq_model.to(device)
80
+ vq_model.eval()
81
+ # utils.load_checkpoint(utils.latest_checkpoint_path(hps.s2_ckpt_dir, "G_*.pth"), vq_model, None, True)
82
+ # utils.load_checkpoint(pretrained_s2G, vq_model, None, True)
83
+ print(
84
+ vq_model.load_state_dict(
85
+ torch.load(pretrained_s2G, map_location="cpu", weights_only=False)["weight"], strict=False
86
+ )
87
+ )
88
+
89
+ def name2go(wav_name, lines):
90
+ hubert_path = "%s/%s.pt" % (hubert_dir, wav_name)
91
+ if os.path.exists(hubert_path) == False:
92
+ return
93
+ ssl_content = torch.load(hubert_path, map_location="cpu")
94
+ if is_half == True:
95
+ ssl_content = ssl_content.half().to(device)
96
+ else:
97
+ ssl_content = ssl_content.to(device)
98
+ codes = vq_model.extract_latent(ssl_content)
99
+ semantic = " ".join([str(i) for i in codes[0, 0, :].tolist()])
100
+ lines.append("%s\t%s" % (wav_name, semantic))
101
+
102
+ with open(inp_text, "r", encoding="utf8") as f:
103
+ lines = f.read().strip("\n").split("\n")
104
+
105
+ lines1 = []
106
+ for line in lines[int(i_part) :: int(all_parts)]:
107
+ # print(line)
108
+ try:
109
+ # wav_name,text=line.split("\t")
110
+ wav_name, spk_name, language, text = line.split("|")
111
+ wav_name = clean_path(wav_name)
112
+ wav_name = os.path.basename(wav_name)
113
+ # name2go(name,lines1)
114
+ name2go(wav_name, lines1)
115
+ except:
116
+ print(line, traceback.format_exc())
117
+ with open(semantic_path, "w", encoding="utf8") as f:
118
+ f.write("\n".join(lines1))
GPT_SoVITS/text/G2PWModel/MONOPHONIC_CHARS.txt ADDED
The diff for this file is too large to render. See raw diff