Spaces:
Running
on
Zero
Running
on
Zero
XXXXRT666
commited on
Commit
·
89584a7
1
Parent(s):
190f22a
Delete Useless Code
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- AR/__init__.py +0 -0
- AR/data/__init__.py +0 -0
- AR/data/bucket_sampler.py +0 -163
- AR/data/data_module.py +0 -76
- AR/data/dataset.py +0 -323
- AR/models/__init__.py +0 -0
- AR/{modules → models}/embedding.py +0 -0
- AR/models/t2s_lightning_module.py +0 -141
- AR/models/t2s_lightning_module_onnx.py +0 -107
- AR/models/t2s_model.py +0 -586
- AR/models/t2s_model_abc.py +2 -2
- AR/models/t2s_model_flash_attn.py +4 -4
- AR/models/t2s_model_onnx.py +0 -338
- AR/modules/__init__.py +0 -0
- AR/modules/activation.py +0 -428
- AR/modules/activation_onnx.py +0 -178
- AR/modules/embedding_onnx.py +0 -63
- AR/modules/lr_schedulers.py +0 -83
- AR/modules/optim.py +0 -622
- AR/modules/patched_mha_with_cache.py +0 -465
- AR/modules/patched_mha_with_cache_onnx.py +0 -92
- AR/modules/scaling.py +0 -335
- AR/modules/transformer.py +0 -378
- AR/modules/transformer_onnx.py +0 -292
- AR/text_processing/__init__.py +0 -0
- AR/text_processing/phonemizer.py +0 -79
- AR/text_processing/symbols.py +0 -10
- AR/utils/__init__.py +0 -37
- AR/utils/initialize.py +0 -38
- AR/utils/io.py +0 -34
- inference_cli.py +0 -55
- inference_gui.py +0 -310
- onnx_export.py +0 -334
- prepare_datasets/1-get-text.py +0 -146
- prepare_datasets/2-get-hubert-wav32k.py +0 -122
- prepare_datasets/3-get-semantic.py +0 -101
- s1_train.py +0 -183
- s2_train.py +0 -601
- tools/__init__.py +0 -0
- tools/asr/config.py +0 -33
- tools/asr/fasterwhisper_asr.py +0 -114
- tools/asr/funasr_asr.py +0 -91
- tools/asr/models/.gitignore +0 -2
- tools/cmd-denoise.py +0 -33
- tools/denoise-model/.gitignore +0 -2
- tools/slice_audio.py +0 -48
- tools/slicer2.py +0 -261
- tools/subfix_webui.py +0 -498
- tools/uvr5/bs_roformer/__init__.py +0 -0
- tools/uvr5/bs_roformer/attend.py +0 -120
AR/__init__.py
DELETED
File without changes
|
AR/data/__init__.py
DELETED
File without changes
|
AR/data/bucket_sampler.py
DELETED
@@ -1,163 +0,0 @@
|
|
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
|
8 |
-
from typing import Optional
|
9 |
-
from typing import TypeVar
|
10 |
-
|
11 |
-
import torch
|
12 |
-
import torch.distributed as dist
|
13 |
-
from torch.utils.data import Dataset
|
14 |
-
from torch.utils.data import Sampler
|
15 |
-
|
16 |
-
__all__ = [
|
17 |
-
"DistributedBucketSampler",
|
18 |
-
]
|
19 |
-
|
20 |
-
T_co = TypeVar("T_co", covariant=True)
|
21 |
-
|
22 |
-
|
23 |
-
class DistributedBucketSampler(Sampler[T_co]):
|
24 |
-
r"""
|
25 |
-
sort the dataset wrt. input length
|
26 |
-
divide samples into buckets
|
27 |
-
sort within buckets
|
28 |
-
divide buckets into batches
|
29 |
-
sort batches
|
30 |
-
"""
|
31 |
-
|
32 |
-
def __init__(
|
33 |
-
self,
|
34 |
-
dataset: Dataset,
|
35 |
-
num_replicas: Optional[int] = None,
|
36 |
-
rank: Optional[int] = None,
|
37 |
-
shuffle: bool = True,
|
38 |
-
seed: int = 0,
|
39 |
-
drop_last: bool = False,
|
40 |
-
batch_size: int = 32,
|
41 |
-
) -> None:
|
42 |
-
if num_replicas is None:
|
43 |
-
if not dist.is_available():
|
44 |
-
raise RuntimeError("Requires distributed package to be available")
|
45 |
-
num_replicas = dist.get_world_size() if torch.cuda.is_available() else 1
|
46 |
-
if rank is None:
|
47 |
-
if not dist.is_available():
|
48 |
-
raise RuntimeError("Requires distributed package to be available")
|
49 |
-
rank = dist.get_rank() if torch.cuda.is_available() else 0
|
50 |
-
if torch.cuda.is_available():
|
51 |
-
torch.cuda.set_device(rank)
|
52 |
-
if rank >= num_replicas or rank < 0:
|
53 |
-
raise ValueError(
|
54 |
-
"Invalid rank {}, rank should be in the interval"
|
55 |
-
" [0, {}]".format(rank, num_replicas - 1)
|
56 |
-
)
|
57 |
-
self.dataset = dataset
|
58 |
-
self.num_replicas = num_replicas
|
59 |
-
self.rank = rank
|
60 |
-
self.epoch = 0
|
61 |
-
self.drop_last = drop_last
|
62 |
-
# If the dataset length is evenly divisible by # of replicas, then there
|
63 |
-
# is no need to drop any data, since the dataset will be split equally.
|
64 |
-
if (
|
65 |
-
self.drop_last and len(self.dataset) % self.num_replicas != 0
|
66 |
-
): # type: ignore[arg-type]
|
67 |
-
# Split to nearest available length that is evenly divisible.
|
68 |
-
# This is to ensure each rank receives the same amount of data when
|
69 |
-
# using this Sampler.
|
70 |
-
self.num_samples = math.ceil(
|
71 |
-
(len(self.dataset) - self.num_replicas)
|
72 |
-
/ self.num_replicas # type: ignore[arg-type]
|
73 |
-
)
|
74 |
-
else:
|
75 |
-
self.num_samples = math.ceil(
|
76 |
-
len(self.dataset) / self.num_replicas
|
77 |
-
) # type: ignore[arg-type]
|
78 |
-
self.total_size = self.num_samples * self.num_replicas
|
79 |
-
self.shuffle = shuffle
|
80 |
-
self.seed = seed
|
81 |
-
self.batch_size = batch_size
|
82 |
-
self.id_with_length = self._get_sample_lengths()
|
83 |
-
self.id_buckets = self.make_buckets(bucket_width=2.0)
|
84 |
-
|
85 |
-
def _get_sample_lengths(self):
|
86 |
-
id_with_lengths = []
|
87 |
-
for i in range(len(self.dataset)):
|
88 |
-
id_with_lengths.append((i, self.dataset.get_sample_length(i)))
|
89 |
-
id_with_lengths.sort(key=lambda x: x[1])
|
90 |
-
return id_with_lengths
|
91 |
-
|
92 |
-
def make_buckets(self, bucket_width: float = 2.0):
|
93 |
-
buckets = []
|
94 |
-
cur = []
|
95 |
-
max_sec = bucket_width
|
96 |
-
for id, sec in self.id_with_length:
|
97 |
-
if sec < max_sec:
|
98 |
-
cur.append(id)
|
99 |
-
else:
|
100 |
-
buckets.append(cur)
|
101 |
-
cur = [id]
|
102 |
-
max_sec += bucket_width
|
103 |
-
if len(cur) > 0:
|
104 |
-
buckets.append(cur)
|
105 |
-
return buckets
|
106 |
-
|
107 |
-
def __iter__(self) -> Iterator[T_co]:
|
108 |
-
if self.shuffle:
|
109 |
-
# deterministically shuffle based on epoch and seed
|
110 |
-
g = torch.Generator()
|
111 |
-
g.manual_seed(self.seed + self.epoch)
|
112 |
-
random.seed(self.epoch + self.seed)
|
113 |
-
shuffled_bucket = []
|
114 |
-
for buc in self.id_buckets:
|
115 |
-
buc_copy = buc.copy()
|
116 |
-
shuffle(buc_copy)
|
117 |
-
shuffled_bucket.append(buc_copy)
|
118 |
-
grouped_batch_size = self.batch_size * self.num_replicas
|
119 |
-
shuffled_bucket = list(itertools.chain(*shuffled_bucket))
|
120 |
-
n_batch = int(math.ceil(len(shuffled_bucket) / grouped_batch_size))
|
121 |
-
batches = [
|
122 |
-
shuffled_bucket[b * grouped_batch_size : (b + 1) * grouped_batch_size]
|
123 |
-
for b in range(n_batch)
|
124 |
-
]
|
125 |
-
shuffle(batches)
|
126 |
-
indices = list(itertools.chain(*batches))
|
127 |
-
else:
|
128 |
-
# type: ignore[arg-type]
|
129 |
-
indices = list(range(len(self.dataset)))
|
130 |
-
|
131 |
-
if not self.drop_last:
|
132 |
-
# add extra samples to make it evenly divisible
|
133 |
-
padding_size = self.total_size - len(indices)
|
134 |
-
if padding_size <= len(indices):
|
135 |
-
indices += indices[:padding_size]
|
136 |
-
else:
|
137 |
-
indices += (indices * math.ceil(padding_size / len(indices)))[
|
138 |
-
:padding_size
|
139 |
-
]
|
140 |
-
else:
|
141 |
-
# remove tail of data to make it evenly divisible.
|
142 |
-
indices = indices[: self.total_size]
|
143 |
-
assert len(indices) == self.total_size
|
144 |
-
|
145 |
-
# subsample
|
146 |
-
indices = indices[self.rank : self.total_size : self.num_replicas]
|
147 |
-
assert len(indices) == self.num_samples
|
148 |
-
|
149 |
-
return iter(indices)
|
150 |
-
|
151 |
-
def __len__(self) -> int:
|
152 |
-
return self.num_samples
|
153 |
-
|
154 |
-
def set_epoch(self, epoch: int) -> None:
|
155 |
-
r"""
|
156 |
-
Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
|
157 |
-
use a different random ordering for each epoch. Otherwise, the next iteration of this
|
158 |
-
sampler will yield the same ordering.
|
159 |
-
|
160 |
-
Args:
|
161 |
-
epoch (int): Epoch number.
|
162 |
-
"""
|
163 |
-
self.epoch = epoch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/data/data_module.py
DELETED
@@ -1,76 +0,0 @@
|
|
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 AR.data.bucket_sampler import DistributedBucketSampler
|
5 |
-
from AR.data.dataset import Text2SemanticDataset
|
6 |
-
from torch.utils.data import DataLoader
|
7 |
-
|
8 |
-
|
9 |
-
class Text2SemanticDataModule(LightningDataModule):
|
10 |
-
def __init__(
|
11 |
-
self,
|
12 |
-
config,
|
13 |
-
train_semantic_path,
|
14 |
-
train_phoneme_path,
|
15 |
-
dev_semantic_path=None,
|
16 |
-
dev_phoneme_path=None,
|
17 |
-
):
|
18 |
-
super().__init__()
|
19 |
-
self.config = config
|
20 |
-
self.train_semantic_path = train_semantic_path
|
21 |
-
self.train_phoneme_path = train_phoneme_path
|
22 |
-
self.dev_semantic_path = dev_semantic_path
|
23 |
-
self.dev_phoneme_path = dev_phoneme_path
|
24 |
-
self.num_workers = self.config["data"]["num_workers"]
|
25 |
-
|
26 |
-
def prepare_data(self):
|
27 |
-
pass
|
28 |
-
|
29 |
-
def setup(self, stage=None, output_logs=False):
|
30 |
-
self._train_dataset = Text2SemanticDataset(
|
31 |
-
phoneme_path=self.train_phoneme_path,
|
32 |
-
semantic_path=self.train_semantic_path,
|
33 |
-
max_sec=self.config["data"]["max_sec"],
|
34 |
-
pad_val=self.config["data"]["pad_val"],
|
35 |
-
)
|
36 |
-
self._dev_dataset = self._train_dataset
|
37 |
-
# self._dev_dataset = Text2SemanticDataset(
|
38 |
-
# phoneme_path=self.dev_phoneme_path,
|
39 |
-
# semantic_path=self.dev_semantic_path,
|
40 |
-
# max_sample=self.config['data']['max_eval_sample'],
|
41 |
-
# max_sec=self.config['data']['max_sec'],
|
42 |
-
# pad_val=self.config['data']['pad_val'])
|
43 |
-
|
44 |
-
def train_dataloader(self):
|
45 |
-
batch_size=self.config["train"]["batch_size"]//2 if self.config["train"].get("if_dpo",False)==True else self.config["train"]["batch_size"]
|
46 |
-
batch_size = max(min(batch_size,len(self._train_dataset)//4),1)#防止不保存
|
47 |
-
sampler = DistributedBucketSampler(self._train_dataset, batch_size=batch_size)
|
48 |
-
return DataLoader(
|
49 |
-
self._train_dataset,
|
50 |
-
batch_size=batch_size,
|
51 |
-
sampler=sampler,
|
52 |
-
collate_fn=self._train_dataset.collate,
|
53 |
-
num_workers=self.num_workers,
|
54 |
-
persistent_workers=True,
|
55 |
-
prefetch_factor=16,
|
56 |
-
)
|
57 |
-
|
58 |
-
def val_dataloader(self):
|
59 |
-
return DataLoader(
|
60 |
-
self._dev_dataset,
|
61 |
-
batch_size=1,
|
62 |
-
shuffle=False,
|
63 |
-
collate_fn=self._train_dataset.collate,
|
64 |
-
num_workers=max(self.num_workers, 12),
|
65 |
-
persistent_workers=True,
|
66 |
-
prefetch_factor=16,
|
67 |
-
)
|
68 |
-
|
69 |
-
# 这个会使用到嘛?
|
70 |
-
def test_dataloader(self):
|
71 |
-
return DataLoader(
|
72 |
-
self._dev_dataset,
|
73 |
-
batch_size=1,
|
74 |
-
shuffle=False,
|
75 |
-
collate_fn=self._train_dataset.collate,
|
76 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/data/dataset.py
DELETED
@@ -1,323 +0,0 @@
|
|
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 |
-
import pdb
|
4 |
-
import sys
|
5 |
-
|
6 |
-
# sys.path.append("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert")
|
7 |
-
import traceback, os
|
8 |
-
from typing import Dict
|
9 |
-
from typing import List
|
10 |
-
|
11 |
-
import numpy as np
|
12 |
-
import pandas as pd
|
13 |
-
import torch, json
|
14 |
-
from torch.utils.data import DataLoader
|
15 |
-
from torch.utils.data import Dataset
|
16 |
-
from transformers import AutoTokenizer
|
17 |
-
|
18 |
-
version = os.environ.get('version',None)
|
19 |
-
|
20 |
-
from text import cleaned_text_to_sequence
|
21 |
-
|
22 |
-
# from config import exp_dir
|
23 |
-
|
24 |
-
|
25 |
-
def batch_sequences(sequences: List[np.array], axis: int = 0, pad_value: int = 0):
|
26 |
-
seq = sequences[0]
|
27 |
-
ndim = seq.ndim
|
28 |
-
if axis < 0:
|
29 |
-
axis += ndim
|
30 |
-
dtype = seq.dtype
|
31 |
-
pad_value = dtype.type(pad_value)
|
32 |
-
seq_lengths = [seq.shape[axis] for seq in sequences]
|
33 |
-
max_length = np.max(seq_lengths)
|
34 |
-
|
35 |
-
padded_sequences = []
|
36 |
-
for seq, length in zip(sequences, seq_lengths):
|
37 |
-
padding = (
|
38 |
-
[(0, 0)] * axis + [(0, max_length - length)] + [(0, 0)] * (ndim - axis - 1)
|
39 |
-
)
|
40 |
-
padded_seq = np.pad(seq, padding, mode="constant", constant_values=pad_value)
|
41 |
-
padded_sequences.append(padded_seq)
|
42 |
-
batch = np.stack(padded_sequences)
|
43 |
-
return batch
|
44 |
-
|
45 |
-
|
46 |
-
class Text2SemanticDataset(Dataset):
|
47 |
-
"""dataset class for text tokens to semantic model training."""
|
48 |
-
|
49 |
-
def __init__(
|
50 |
-
self,
|
51 |
-
phoneme_path: str,
|
52 |
-
semantic_path: str,
|
53 |
-
max_sample: int = None,
|
54 |
-
max_sec: int = 100,
|
55 |
-
pad_val: int = 1024,
|
56 |
-
# min value of phoneme/sec
|
57 |
-
min_ps_ratio: int = 3,
|
58 |
-
# max value of phoneme/sec
|
59 |
-
max_ps_ratio: int = 25,
|
60 |
-
) -> None:
|
61 |
-
super().__init__()
|
62 |
-
|
63 |
-
self.semantic_data = pd.read_csv(
|
64 |
-
semantic_path, delimiter="\t", encoding="utf-8"
|
65 |
-
)
|
66 |
-
# get dict
|
67 |
-
self.path2 = phoneme_path # "%s/2-name2text.txt"%exp_dir#phoneme_path
|
68 |
-
self.path3 = "%s/3-bert" % (
|
69 |
-
os.path.dirname(phoneme_path)
|
70 |
-
) # "%s/3-bert"%exp_dir#bert_dir
|
71 |
-
self.path6 = semantic_path # "%s/6-name2semantic.tsv"%exp_dir#semantic_path
|
72 |
-
assert os.path.exists(self.path2)
|
73 |
-
assert os.path.exists(self.path6)
|
74 |
-
self.phoneme_data = {}
|
75 |
-
with open(self.path2, "r", encoding="utf8") as f:
|
76 |
-
lines = f.read().strip("\n").split("\n")
|
77 |
-
|
78 |
-
for line in lines:
|
79 |
-
tmp = line.split("\t")
|
80 |
-
if len(tmp) != 4:
|
81 |
-
continue
|
82 |
-
self.phoneme_data[tmp[0]] = [tmp[1], tmp[2], tmp[3]]
|
83 |
-
|
84 |
-
# self.phoneme_data = np.load(phoneme_path, allow_pickle=True).item()
|
85 |
-
# pad for semantic tokens
|
86 |
-
self.PAD: int = pad_val
|
87 |
-
# self.hz = 25
|
88 |
-
# with open("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert/configs/s2.json", "r") as f:data = f.read()
|
89 |
-
# data=json.loads(data)["model"]["semantic_frame_rate"]#50hz
|
90 |
-
# self.hz=int(data[:-2])#
|
91 |
-
self.hz = int(os.environ.get("hz", "25hz")[:-2])
|
92 |
-
|
93 |
-
# max seconds of semantic token
|
94 |
-
self.max_sec = max_sec
|
95 |
-
self.min_ps_ratio = min_ps_ratio
|
96 |
-
self.max_ps_ratio = max_ps_ratio
|
97 |
-
|
98 |
-
if max_sample is not None:
|
99 |
-
self.semantic_data = self.semantic_data[:max_sample]
|
100 |
-
|
101 |
-
# {idx: (semantic, phoneme)}
|
102 |
-
# semantic list, phoneme list
|
103 |
-
self.semantic_phoneme = []
|
104 |
-
self.item_names = []
|
105 |
-
|
106 |
-
self.inited = False
|
107 |
-
|
108 |
-
if not self.inited:
|
109 |
-
# 调用初始化函数
|
110 |
-
self.init_batch()
|
111 |
-
self.inited = True
|
112 |
-
del self.semantic_data
|
113 |
-
del self.phoneme_data
|
114 |
-
# self.tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext-large")
|
115 |
-
# self.tokenizer = AutoTokenizer.from_pretrained("/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large")
|
116 |
-
|
117 |
-
def init_batch(self):
|
118 |
-
semantic_data_len = len(self.semantic_data)
|
119 |
-
phoneme_data_len = len(self.phoneme_data.keys())
|
120 |
-
print("semantic_data_len:", semantic_data_len)
|
121 |
-
print("phoneme_data_len:", phoneme_data_len)
|
122 |
-
print(self.semantic_data)
|
123 |
-
idx = 0
|
124 |
-
num_not_in = 0
|
125 |
-
num_deleted_bigger = 0
|
126 |
-
num_deleted_ps = 0
|
127 |
-
for i in range(semantic_data_len):
|
128 |
-
# 先依次遍历
|
129 |
-
# get str
|
130 |
-
item_name = self.semantic_data.iloc[i,0]
|
131 |
-
# print(self.phoneme_data)
|
132 |
-
try:
|
133 |
-
phoneme, word2ph, text = self.phoneme_data[item_name]
|
134 |
-
except Exception:
|
135 |
-
traceback.print_exc()
|
136 |
-
# print(f"{item_name} not in self.phoneme_data !")
|
137 |
-
num_not_in += 1
|
138 |
-
continue
|
139 |
-
|
140 |
-
semantic_str = self.semantic_data.iloc[i,1]
|
141 |
-
# get token list
|
142 |
-
semantic_ids = [int(idx) for idx in semantic_str.split(" ")]
|
143 |
-
# (T), 是否需要变成 (1, T) -> 不需要,因为需要求 len
|
144 |
-
# 过滤掉太长的样本
|
145 |
-
if (
|
146 |
-
len(semantic_ids) > self.max_sec * self.hz
|
147 |
-
): #########1###根据token个数推测总时长过滤时长60s(config里)#40*25=1k
|
148 |
-
num_deleted_bigger += 1
|
149 |
-
continue
|
150 |
-
# (T, ), 这个速度不会很慢,所以可以在一开始就处理,无需在 __getitem__ 里面单个处理####
|
151 |
-
phoneme = phoneme.split(" ")
|
152 |
-
|
153 |
-
try:
|
154 |
-
phoneme_ids = cleaned_text_to_sequence(phoneme, version)
|
155 |
-
except:
|
156 |
-
traceback.print_exc()
|
157 |
-
# print(f"{item_name} not in self.phoneme_data !")
|
158 |
-
num_not_in += 1
|
159 |
-
continue
|
160 |
-
# if len(phoneme_ids) >400:###########2:改为恒定限制为semantic/2.5就行
|
161 |
-
if (
|
162 |
-
len(phoneme_ids) > self.max_sec * self.hz / 2.5
|
163 |
-
): ###########2:改为恒定限制为semantic/2.5就行
|
164 |
-
num_deleted_ps += 1
|
165 |
-
continue
|
166 |
-
# if len(semantic_ids) > 1000:###########3
|
167 |
-
# num_deleted_bigger += 1
|
168 |
-
# continue
|
169 |
-
|
170 |
-
ps_ratio = len(phoneme_ids) / (len(semantic_ids) / self.hz)
|
171 |
-
|
172 |
-
if (
|
173 |
-
ps_ratio > self.max_ps_ratio or ps_ratio < self.min_ps_ratio
|
174 |
-
): ##########4#3~25#每秒多少个phone
|
175 |
-
num_deleted_ps += 1
|
176 |
-
# print(item_name)
|
177 |
-
continue
|
178 |
-
|
179 |
-
self.semantic_phoneme.append((semantic_ids, phoneme_ids))
|
180 |
-
idx += 1
|
181 |
-
self.item_names.append(item_name)
|
182 |
-
|
183 |
-
min_num = 100 # 20直接不补#30补了也不存ckpt
|
184 |
-
leng = len(self.semantic_phoneme)
|
185 |
-
if leng < min_num:
|
186 |
-
tmp1 = self.semantic_phoneme
|
187 |
-
tmp2 = self.item_names
|
188 |
-
self.semantic_phoneme = []
|
189 |
-
self.item_names = []
|
190 |
-
for _ in range(max(2, int(min_num / leng))):
|
191 |
-
self.semantic_phoneme += tmp1
|
192 |
-
self.item_names += tmp2
|
193 |
-
if num_not_in > 0:
|
194 |
-
print(f"there are {num_not_in} semantic datas not in phoneme datas")
|
195 |
-
if num_deleted_bigger > 0:
|
196 |
-
print(
|
197 |
-
f"deleted {num_deleted_bigger} audios who's duration are bigger than {self.max_sec} seconds"
|
198 |
-
)
|
199 |
-
if num_deleted_ps > 0:
|
200 |
-
# 4702 for LibriTTS, LirbriTTS 是标注数据, 是否需要筛?=> 需要,有值为 100 的极端值
|
201 |
-
print(
|
202 |
-
f"deleted {num_deleted_ps} audios who's phoneme/sec are bigger than {self.max_ps_ratio} or smaller than {self.min_ps_ratio}"
|
203 |
-
)
|
204 |
-
"""
|
205 |
-
there are 31 semantic datas not in phoneme datas
|
206 |
-
deleted 34 audios who's duration are bigger than 54 seconds
|
207 |
-
deleted 3190 audios who's phoneme/sec are bigger than 25 or smaller than 3
|
208 |
-
dataset.__len__(): 366463
|
209 |
-
|
210 |
-
"""
|
211 |
-
# 345410 for LibriTTS
|
212 |
-
print("dataset.__len__():", self.__len__())
|
213 |
-
|
214 |
-
def __get_item_names__(self) -> List[str]:
|
215 |
-
return self.item_names
|
216 |
-
|
217 |
-
def __len__(self) -> int:
|
218 |
-
return len(self.semantic_phoneme)
|
219 |
-
|
220 |
-
def __getitem__(self, idx: int) -> Dict:
|
221 |
-
semantic_ids, phoneme_ids = self.semantic_phoneme[idx]
|
222 |
-
item_name = self.item_names[idx]
|
223 |
-
phoneme_ids_len = len(phoneme_ids)
|
224 |
-
# semantic tokens target
|
225 |
-
semantic_ids_len = len(semantic_ids)
|
226 |
-
|
227 |
-
flag = 0
|
228 |
-
path_bert = "%s/%s.pt" % (self.path3, item_name)
|
229 |
-
if os.path.exists(path_bert) == True:
|
230 |
-
bert_feature = torch.load(path_bert, map_location="cpu")
|
231 |
-
else:
|
232 |
-
flag = 1
|
233 |
-
if flag == 1:
|
234 |
-
# bert_feature=torch.zeros_like(phoneme_ids,dtype=torch.float32)
|
235 |
-
bert_feature = None
|
236 |
-
else:
|
237 |
-
assert bert_feature.shape[-1] == len(phoneme_ids)
|
238 |
-
return {
|
239 |
-
"idx": idx,
|
240 |
-
"phoneme_ids": phoneme_ids,
|
241 |
-
"phoneme_ids_len": phoneme_ids_len,
|
242 |
-
"semantic_ids": semantic_ids,
|
243 |
-
"semantic_ids_len": semantic_ids_len,
|
244 |
-
"bert_feature": bert_feature,
|
245 |
-
}
|
246 |
-
|
247 |
-
def get_sample_length(self, idx: int):
|
248 |
-
semantic_ids = self.semantic_phoneme[idx][0]
|
249 |
-
sec = 1.0 * len(semantic_ids) / self.hz
|
250 |
-
return sec
|
251 |
-
|
252 |
-
def collate(self, examples: List[Dict]) -> Dict:
|
253 |
-
sample_index: List[int] = []
|
254 |
-
phoneme_ids: List[torch.Tensor] = []
|
255 |
-
phoneme_ids_lens: List[int] = []
|
256 |
-
semantic_ids: List[torch.Tensor] = []
|
257 |
-
semantic_ids_lens: List[int] = []
|
258 |
-
# return
|
259 |
-
|
260 |
-
for item in examples:
|
261 |
-
sample_index.append(item["idx"])
|
262 |
-
phoneme_ids.append(np.array(item["phoneme_ids"], dtype=np.int64))
|
263 |
-
semantic_ids.append(np.array(item["semantic_ids"], dtype=np.int64))
|
264 |
-
phoneme_ids_lens.append(item["phoneme_ids_len"])
|
265 |
-
semantic_ids_lens.append(item["semantic_ids_len"])
|
266 |
-
|
267 |
-
# pad 0
|
268 |
-
phoneme_ids = batch_sequences(phoneme_ids)
|
269 |
-
semantic_ids = batch_sequences(semantic_ids, pad_value=self.PAD)
|
270 |
-
|
271 |
-
# # convert each batch to torch.tensor
|
272 |
-
phoneme_ids = torch.tensor(phoneme_ids)
|
273 |
-
semantic_ids = torch.tensor(semantic_ids)
|
274 |
-
phoneme_ids_lens = torch.tensor(phoneme_ids_lens)
|
275 |
-
semantic_ids_lens = torch.tensor(semantic_ids_lens)
|
276 |
-
bert_padded = torch.FloatTensor(len(examples), 1024, max(phoneme_ids_lens))
|
277 |
-
bert_padded.zero_()
|
278 |
-
|
279 |
-
for idx, item in enumerate(examples):
|
280 |
-
bert = item["bert_feature"]
|
281 |
-
if bert != None:
|
282 |
-
bert_padded[idx, :, : bert.shape[-1]] = bert
|
283 |
-
|
284 |
-
return {
|
285 |
-
# List[int]
|
286 |
-
"ids": sample_index,
|
287 |
-
# torch.Tensor (B, max_phoneme_length)
|
288 |
-
"phoneme_ids": phoneme_ids,
|
289 |
-
# torch.Tensor (B)
|
290 |
-
"phoneme_ids_len": phoneme_ids_lens,
|
291 |
-
# torch.Tensor (B, max_semantic_ids_length)
|
292 |
-
"semantic_ids": semantic_ids,
|
293 |
-
# torch.Tensor (B)
|
294 |
-
"semantic_ids_len": semantic_ids_lens,
|
295 |
-
# torch.Tensor (B, 1024, max_phoneme_length)
|
296 |
-
"bert_feature": bert_padded,
|
297 |
-
}
|
298 |
-
|
299 |
-
|
300 |
-
if __name__ == "__main__":
|
301 |
-
root_dir = "/data/docker/liujing04/gpt-vits/prepare/dump_mix/"
|
302 |
-
dataset = Text2SemanticDataset(
|
303 |
-
phoneme_path=root_dir + "phoneme_train.npy",
|
304 |
-
semantic_path=root_dir + "semantic_train.tsv",
|
305 |
-
)
|
306 |
-
|
307 |
-
batch_size = 12
|
308 |
-
dataloader = DataLoader(
|
309 |
-
dataset, batch_size=batch_size, collate_fn=dataset.collate, shuffle=False
|
310 |
-
)
|
311 |
-
for i, batch in enumerate(dataloader):
|
312 |
-
if i % 1000 == 0:
|
313 |
-
print(i)
|
314 |
-
# if i == 0:
|
315 |
-
# print('batch["ids"]:', batch["ids"])
|
316 |
-
# print('batch["phoneme_ids"]:', batch["phoneme_ids"],
|
317 |
-
# batch["phoneme_ids"].shape)
|
318 |
-
# print('batch["phoneme_ids_len"]:', batch["phoneme_ids_len"],
|
319 |
-
# batch["phoneme_ids_len"].shape)
|
320 |
-
# print('batch["semantic_ids"]:', batch["semantic_ids"],
|
321 |
-
# batch["semantic_ids"].shape)
|
322 |
-
# print('batch["semantic_ids_len"]:', batch["semantic_ids_len"],
|
323 |
-
# batch["semantic_ids_len"].shape)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/models/__init__.py
DELETED
File without changes
|
AR/{modules → models}/embedding.py
RENAMED
File without changes
|
AR/models/t2s_lightning_module.py
DELETED
@@ -1,141 +0,0 @@
|
|
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, sys
|
4 |
-
|
5 |
-
now_dir = os.getcwd()
|
6 |
-
sys.path.append(now_dir)
|
7 |
-
from typing import Dict
|
8 |
-
|
9 |
-
import torch
|
10 |
-
from pytorch_lightning import LightningModule
|
11 |
-
from AR.models.t2s_model import Text2SemanticDecoder
|
12 |
-
from AR.modules.lr_schedulers import WarmupCosineLRSchedule
|
13 |
-
from AR.modules.optim import ScaledAdam
|
14 |
-
|
15 |
-
class Text2SemanticLightningModule(LightningModule):
|
16 |
-
def __init__(self, config, output_dir, is_train=True):
|
17 |
-
super().__init__()
|
18 |
-
self.config = config
|
19 |
-
self.top_k = 3
|
20 |
-
self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
|
21 |
-
pretrained_s1 = config.get("pretrained_s1")
|
22 |
-
if pretrained_s1 and is_train:
|
23 |
-
# print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
|
24 |
-
print(
|
25 |
-
self.load_state_dict(
|
26 |
-
torch.load(pretrained_s1, map_location="cpu")["weight"]
|
27 |
-
)
|
28 |
-
)
|
29 |
-
if is_train:
|
30 |
-
self.automatic_optimization = False
|
31 |
-
self.save_hyperparameters()
|
32 |
-
self.eval_dir = output_dir / "eval"
|
33 |
-
self.eval_dir.mkdir(parents=True, exist_ok=True)
|
34 |
-
|
35 |
-
def training_step(self, batch: Dict, batch_idx: int):
|
36 |
-
opt = self.optimizers()
|
37 |
-
scheduler = self.lr_schedulers()
|
38 |
-
forward=self.model.forward if self.config["train"].get("if_dpo",False)==True else self.model.forward_old
|
39 |
-
loss, acc = forward(
|
40 |
-
batch["phoneme_ids"],
|
41 |
-
batch["phoneme_ids_len"],
|
42 |
-
batch["semantic_ids"],
|
43 |
-
batch["semantic_ids_len"],
|
44 |
-
batch["bert_feature"],
|
45 |
-
)
|
46 |
-
self.manual_backward(loss)
|
47 |
-
if batch_idx > 0 and batch_idx % 4 == 0:
|
48 |
-
opt.step()
|
49 |
-
opt.zero_grad()
|
50 |
-
scheduler.step()
|
51 |
-
|
52 |
-
self.log(
|
53 |
-
"total_loss",
|
54 |
-
loss,
|
55 |
-
on_step=True,
|
56 |
-
on_epoch=True,
|
57 |
-
prog_bar=True,
|
58 |
-
sync_dist=True,
|
59 |
-
)
|
60 |
-
self.log(
|
61 |
-
"lr",
|
62 |
-
scheduler.get_last_lr()[0],
|
63 |
-
on_epoch=True,
|
64 |
-
prog_bar=True,
|
65 |
-
sync_dist=True,
|
66 |
-
)
|
67 |
-
self.log(
|
68 |
-
f"top_{self.top_k}_acc",
|
69 |
-
acc,
|
70 |
-
on_step=True,
|
71 |
-
on_epoch=True,
|
72 |
-
prog_bar=True,
|
73 |
-
sync_dist=True,
|
74 |
-
)
|
75 |
-
|
76 |
-
def validation_step(self, batch: Dict, batch_idx: int):
|
77 |
-
return
|
78 |
-
|
79 |
-
# # get loss
|
80 |
-
# loss, acc = self.model.forward(
|
81 |
-
# batch['phoneme_ids'], batch['phoneme_ids_len'],
|
82 |
-
# batch['semantic_ids'], batch['semantic_ids_len'],
|
83 |
-
# batch['bert_feature']
|
84 |
-
# )
|
85 |
-
#
|
86 |
-
# self.log(
|
87 |
-
# "val_total_loss",
|
88 |
-
# loss,
|
89 |
-
# on_step=True,
|
90 |
-
# on_epoch=True,
|
91 |
-
# prog_bar=True,
|
92 |
-
# sync_dist=True)
|
93 |
-
# self.log(
|
94 |
-
# f"val_top_{self.top_k}_acc",
|
95 |
-
# acc,
|
96 |
-
# on_step=True,
|
97 |
-
# on_epoch=True,
|
98 |
-
# prog_bar=True,
|
99 |
-
# sync_dist=True)
|
100 |
-
#
|
101 |
-
# # get infer output
|
102 |
-
# semantic_len = batch['semantic_ids'].size(1)
|
103 |
-
# prompt_len = min(int(semantic_len * 0.5), 150)
|
104 |
-
# prompt = batch['semantic_ids'][:, :prompt_len]
|
105 |
-
# pred_semantic = self.model.infer(batch['phoneme_ids'],
|
106 |
-
# batch['phoneme_ids_len'], prompt,
|
107 |
-
# batch['bert_feature']
|
108 |
-
# )
|
109 |
-
# save_name = f'semantic_toks_{batch_idx}.pt'
|
110 |
-
# save_path = os.path.join(self.eval_dir, save_name)
|
111 |
-
# torch.save(pred_semantic.detach().cpu(), save_path)
|
112 |
-
|
113 |
-
def configure_optimizers(self):
|
114 |
-
model_parameters = self.model.parameters()
|
115 |
-
parameters_names = []
|
116 |
-
parameters_names.append(
|
117 |
-
[name_param_pair[0] for name_param_pair in self.model.named_parameters()]
|
118 |
-
)
|
119 |
-
lm_opt = ScaledAdam(
|
120 |
-
model_parameters,
|
121 |
-
lr=0.01,
|
122 |
-
betas=(0.9, 0.95),
|
123 |
-
clipping_scale=2.0,
|
124 |
-
parameters_names=parameters_names,
|
125 |
-
show_dominant_parameters=False,
|
126 |
-
clipping_update_period=1000,
|
127 |
-
)
|
128 |
-
|
129 |
-
return {
|
130 |
-
"optimizer": lm_opt,
|
131 |
-
"lr_scheduler": {
|
132 |
-
"scheduler": WarmupCosineLRSchedule(
|
133 |
-
lm_opt,
|
134 |
-
init_lr=self.config["optimizer"]["lr_init"],
|
135 |
-
peak_lr=self.config["optimizer"]["lr"],
|
136 |
-
end_lr=self.config["optimizer"]["lr_end"],
|
137 |
-
warmup_steps=self.config["optimizer"]["warmup_steps"],
|
138 |
-
total_steps=self.config["optimizer"]["decay_steps"],
|
139 |
-
)
|
140 |
-
},
|
141 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/models/t2s_lightning_module_onnx.py
DELETED
@@ -1,107 +0,0 @@
|
|
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, sys
|
4 |
-
|
5 |
-
now_dir = os.getcwd()
|
6 |
-
sys.path.append(now_dir)
|
7 |
-
from typing import Dict
|
8 |
-
|
9 |
-
import torch
|
10 |
-
from pytorch_lightning import LightningModule
|
11 |
-
from AR.models.t2s_model_onnx import Text2SemanticDecoder
|
12 |
-
from AR.modules.lr_schedulers import WarmupCosineLRSchedule
|
13 |
-
from AR.modules.optim import ScaledAdam
|
14 |
-
|
15 |
-
|
16 |
-
class Text2SemanticLightningModule(LightningModule):
|
17 |
-
def __init__(self, config, output_dir, is_train=True):
|
18 |
-
super().__init__()
|
19 |
-
self.config = config
|
20 |
-
self.top_k = 3
|
21 |
-
self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
|
22 |
-
pretrained_s1 = config.get("pretrained_s1")
|
23 |
-
if pretrained_s1 and is_train:
|
24 |
-
# print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
|
25 |
-
print(
|
26 |
-
self.load_state_dict(
|
27 |
-
torch.load(pretrained_s1, map_location="cpu")["weight"]
|
28 |
-
)
|
29 |
-
)
|
30 |
-
if is_train:
|
31 |
-
self.automatic_optimization = False
|
32 |
-
self.save_hyperparameters()
|
33 |
-
self.eval_dir = output_dir / "eval"
|
34 |
-
self.eval_dir.mkdir(parents=True, exist_ok=True)
|
35 |
-
|
36 |
-
def training_step(self, batch: Dict, batch_idx: int):
|
37 |
-
opt = self.optimizers()
|
38 |
-
scheduler = self.lr_schedulers()
|
39 |
-
loss, acc = self.model.forward(
|
40 |
-
batch["phoneme_ids"],
|
41 |
-
batch["phoneme_ids_len"],
|
42 |
-
batch["semantic_ids"],
|
43 |
-
batch["semantic_ids_len"],
|
44 |
-
batch["bert_feature"],
|
45 |
-
)
|
46 |
-
self.manual_backward(loss)
|
47 |
-
if batch_idx > 0 and batch_idx % 4 == 0:
|
48 |
-
opt.step()
|
49 |
-
opt.zero_grad()
|
50 |
-
scheduler.step()
|
51 |
-
|
52 |
-
self.log(
|
53 |
-
"total_loss",
|
54 |
-
loss,
|
55 |
-
on_step=True,
|
56 |
-
on_epoch=True,
|
57 |
-
prog_bar=True,
|
58 |
-
sync_dist=True,
|
59 |
-
)
|
60 |
-
self.log(
|
61 |
-
"lr",
|
62 |
-
scheduler.get_last_lr()[0],
|
63 |
-
on_epoch=True,
|
64 |
-
prog_bar=True,
|
65 |
-
sync_dist=True,
|
66 |
-
)
|
67 |
-
self.log(
|
68 |
-
f"top_{self.top_k}_acc",
|
69 |
-
acc,
|
70 |
-
on_step=True,
|
71 |
-
on_epoch=True,
|
72 |
-
prog_bar=True,
|
73 |
-
sync_dist=True,
|
74 |
-
)
|
75 |
-
|
76 |
-
def validation_step(self, batch: Dict, batch_idx: int):
|
77 |
-
return
|
78 |
-
|
79 |
-
def configure_optimizers(self):
|
80 |
-
model_parameters = self.model.parameters()
|
81 |
-
parameters_names = []
|
82 |
-
parameters_names.append(
|
83 |
-
[name_param_pair[0] for name_param_pair in self.model.named_parameters()]
|
84 |
-
)
|
85 |
-
lm_opt = ScaledAdam(
|
86 |
-
model_parameters,
|
87 |
-
lr=0.01,
|
88 |
-
betas=(0.9, 0.95),
|
89 |
-
clipping_scale=2.0,
|
90 |
-
parameters_names=parameters_names,
|
91 |
-
show_dominant_parameters=False,
|
92 |
-
clipping_update_period=1000,
|
93 |
-
)
|
94 |
-
|
95 |
-
return {
|
96 |
-
"optimizer": lm_opt,
|
97 |
-
"lr_scheduler": {
|
98 |
-
"scheduler": WarmupCosineLRSchedule(
|
99 |
-
lm_opt,
|
100 |
-
init_lr=self.config["optimizer"]["lr_init"],
|
101 |
-
peak_lr=self.config["optimizer"]["lr"],
|
102 |
-
end_lr=self.config["optimizer"]["lr_end"],
|
103 |
-
warmup_steps=self.config["optimizer"]["warmup_steps"],
|
104 |
-
total_steps=self.config["optimizer"]["decay_steps"],
|
105 |
-
)
|
106 |
-
},
|
107 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/models/t2s_model.py
DELETED
@@ -1,586 +0,0 @@
|
|
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 |
-
import random
|
5 |
-
import numpy as np
|
6 |
-
|
7 |
-
from tqdm import tqdm
|
8 |
-
from typing import List
|
9 |
-
from AR.models.utils import make_pad_mask
|
10 |
-
from AR.models.utils import (
|
11 |
-
topk_sampling,
|
12 |
-
sample,
|
13 |
-
logits_to_probs,
|
14 |
-
multinomial_sample_one_no_sync,
|
15 |
-
dpo_loss,
|
16 |
-
make_reject_y,
|
17 |
-
get_batch_logps
|
18 |
-
)
|
19 |
-
from AR.modules.embedding import SinePositionalEmbedding
|
20 |
-
from AR.modules.embedding import TokenEmbedding
|
21 |
-
from AR.modules.transformer import LayerNorm
|
22 |
-
from AR.modules.transformer import TransformerEncoder
|
23 |
-
from AR.modules.transformer import TransformerEncoderLayer
|
24 |
-
from torch import nn
|
25 |
-
from torch.nn import functional as F
|
26 |
-
from torchmetrics.classification import MulticlassAccuracy
|
27 |
-
|
28 |
-
default_config = {
|
29 |
-
"embedding_dim": 512,
|
30 |
-
"hidden_dim": 512,
|
31 |
-
"num_head": 8,
|
32 |
-
"num_layers": 12,
|
33 |
-
"num_codebook": 8,
|
34 |
-
"p_dropout": 0.0,
|
35 |
-
"vocab_size": 1024 + 1,
|
36 |
-
"phoneme_vocab_size": 512,
|
37 |
-
"EOS": 1024,
|
38 |
-
}
|
39 |
-
|
40 |
-
|
41 |
-
@torch.jit.script
|
42 |
-
class T2SMLP:
|
43 |
-
def __init__(self, w1, b1, w2, b2):
|
44 |
-
self.w1 = w1
|
45 |
-
self.b1 = b1
|
46 |
-
self.w2 = w2
|
47 |
-
self.b2 = b2
|
48 |
-
|
49 |
-
def forward(self, x):
|
50 |
-
x = F.relu(F.linear(x, self.w1, self.b1))
|
51 |
-
x = F.linear(x, self.w2, self.b2)
|
52 |
-
return x
|
53 |
-
|
54 |
-
|
55 |
-
@torch.jit.script
|
56 |
-
class T2SBlock:
|
57 |
-
def __init__(
|
58 |
-
self,
|
59 |
-
num_heads,
|
60 |
-
hidden_dim: int,
|
61 |
-
mlp: T2SMLP,
|
62 |
-
qkv_w,
|
63 |
-
qkv_b,
|
64 |
-
out_w,
|
65 |
-
out_b,
|
66 |
-
norm_w1,
|
67 |
-
norm_b1,
|
68 |
-
norm_eps1,
|
69 |
-
norm_w2,
|
70 |
-
norm_b2,
|
71 |
-
norm_eps2,
|
72 |
-
):
|
73 |
-
self.num_heads = num_heads
|
74 |
-
self.mlp = mlp
|
75 |
-
self.hidden_dim: int = hidden_dim
|
76 |
-
self.qkv_w = qkv_w
|
77 |
-
self.qkv_b = qkv_b
|
78 |
-
self.out_w = out_w
|
79 |
-
self.out_b = out_b
|
80 |
-
self.norm_w1 = norm_w1
|
81 |
-
self.norm_b1 = norm_b1
|
82 |
-
self.norm_eps1 = norm_eps1
|
83 |
-
self.norm_w2 = norm_w2
|
84 |
-
self.norm_b2 = norm_b2
|
85 |
-
self.norm_eps2 = norm_eps2
|
86 |
-
|
87 |
-
def process_prompt(self, x, attn_mask: torch.Tensor):
|
88 |
-
q, k, v = F.linear(x, self.qkv_w, self.qkv_b).chunk(3, dim=-1)
|
89 |
-
|
90 |
-
batch_size = q.shape[0]
|
91 |
-
q_len = q.shape[1]
|
92 |
-
kv_len = k.shape[1]
|
93 |
-
|
94 |
-
k_cache = k
|
95 |
-
v_cache = v
|
96 |
-
|
97 |
-
q = q.view(batch_size, q_len, self.num_heads, -1).transpose(1, 2)
|
98 |
-
k = k_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
|
99 |
-
v = v_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
|
100 |
-
|
101 |
-
attn = F.scaled_dot_product_attention(q, k, v, ~attn_mask)
|
102 |
-
|
103 |
-
attn = attn.permute(2, 0, 1, 3).reshape(batch_size, -1, self.hidden_dim)
|
104 |
-
attn = F.linear(attn, self.out_w, self.out_b)
|
105 |
-
|
106 |
-
x = F.layer_norm(
|
107 |
-
x + attn, [self.hidden_dim], self.norm_w1, self.norm_b1, self.norm_eps1
|
108 |
-
)
|
109 |
-
x = F.layer_norm(
|
110 |
-
x + self.mlp.forward(x),
|
111 |
-
[self.hidden_dim],
|
112 |
-
self.norm_w2,
|
113 |
-
self.norm_b2,
|
114 |
-
self.norm_eps2,
|
115 |
-
)
|
116 |
-
return x, k_cache, v_cache
|
117 |
-
|
118 |
-
def decode_next_token(self, x, k_cache, v_cache):
|
119 |
-
q, k, v = F.linear(x, self.qkv_w, self.qkv_b).chunk(3, dim=-1)
|
120 |
-
|
121 |
-
k_cache = torch.cat([k_cache, k], dim=1)
|
122 |
-
v_cache = torch.cat([v_cache, v], dim=1)
|
123 |
-
kv_len = k_cache.shape[1]
|
124 |
-
|
125 |
-
batch_size = q.shape[0]
|
126 |
-
q_len = q.shape[1]
|
127 |
-
|
128 |
-
q = q.view(batch_size, q_len, self.num_heads, -1).transpose(1, 2)
|
129 |
-
k = k_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
|
130 |
-
v = v_cache.view(batch_size, kv_len, self.num_heads, -1).transpose(1, 2)
|
131 |
-
|
132 |
-
attn = F.scaled_dot_product_attention(q, k, v)
|
133 |
-
|
134 |
-
attn = attn.permute(2, 0, 1, 3).reshape(batch_size, -1, self.hidden_dim)
|
135 |
-
attn = F.linear(attn, self.out_w, self.out_b)
|
136 |
-
|
137 |
-
x = F.layer_norm(
|
138 |
-
x + attn, [self.hidden_dim], self.norm_w1, self.norm_b1, self.norm_eps1
|
139 |
-
)
|
140 |
-
x = F.layer_norm(
|
141 |
-
x + self.mlp.forward(x),
|
142 |
-
[self.hidden_dim],
|
143 |
-
self.norm_w2,
|
144 |
-
self.norm_b2,
|
145 |
-
self.norm_eps2,
|
146 |
-
)
|
147 |
-
return x, k_cache, v_cache
|
148 |
-
|
149 |
-
|
150 |
-
@torch.jit.script
|
151 |
-
class T2STransformer:
|
152 |
-
def __init__(self, num_blocks: int, blocks: List[T2SBlock]):
|
153 |
-
self.num_blocks: int = num_blocks
|
154 |
-
self.blocks = blocks
|
155 |
-
|
156 |
-
def process_prompt(
|
157 |
-
self, x, attn_mask: torch.Tensor):
|
158 |
-
k_cache: List[torch.Tensor] = []
|
159 |
-
v_cache: List[torch.Tensor] = []
|
160 |
-
for i in range(self.num_blocks):
|
161 |
-
x, k_cache_, v_cache_ = self.blocks[i].process_prompt(x, attn_mask)
|
162 |
-
k_cache.append(k_cache_)
|
163 |
-
v_cache.append(v_cache_)
|
164 |
-
return x, k_cache, v_cache
|
165 |
-
|
166 |
-
def decode_next_token(
|
167 |
-
self, x, k_cache: List[torch.Tensor], v_cache: List[torch.Tensor]
|
168 |
-
):
|
169 |
-
for i in range(self.num_blocks):
|
170 |
-
x, k_cache[i], v_cache[i] = self.blocks[i].decode_next_token(x, k_cache[i], v_cache[i])
|
171 |
-
return x, k_cache, v_cache
|
172 |
-
|
173 |
-
|
174 |
-
class Text2SemanticDecoder(nn.Module):
|
175 |
-
def __init__(self, config, norm_first=False, top_k=3):
|
176 |
-
super(Text2SemanticDecoder, self).__init__()
|
177 |
-
self.model_dim = config["model"]["hidden_dim"]
|
178 |
-
self.embedding_dim = config["model"]["embedding_dim"]
|
179 |
-
self.num_head = config["model"]["head"]
|
180 |
-
self.num_layers = config["model"]["n_layer"]
|
181 |
-
self.norm_first = norm_first
|
182 |
-
self.vocab_size = config["model"]["vocab_size"]
|
183 |
-
self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
|
184 |
-
self.p_dropout = config["model"]["dropout"]
|
185 |
-
self.EOS = config["model"]["EOS"]
|
186 |
-
self.norm_first = norm_first
|
187 |
-
assert self.EOS == self.vocab_size - 1
|
188 |
-
# should be same as num of kmeans bin
|
189 |
-
# assert self.EOS == 1024
|
190 |
-
self.bert_proj = nn.Linear(1024, self.embedding_dim)
|
191 |
-
self.ar_text_embedding = TokenEmbedding(
|
192 |
-
self.embedding_dim, self.phoneme_vocab_size, self.p_dropout
|
193 |
-
)
|
194 |
-
self.ar_text_position = SinePositionalEmbedding(
|
195 |
-
self.embedding_dim, dropout=0.1, scale=False, alpha=True
|
196 |
-
)
|
197 |
-
self.ar_audio_embedding = TokenEmbedding(
|
198 |
-
self.embedding_dim, self.vocab_size, self.p_dropout
|
199 |
-
)
|
200 |
-
self.ar_audio_position = SinePositionalEmbedding(
|
201 |
-
self.embedding_dim, dropout=0.1, scale=False, alpha=True
|
202 |
-
)
|
203 |
-
|
204 |
-
self.h = TransformerEncoder(
|
205 |
-
TransformerEncoderLayer(
|
206 |
-
d_model=self.model_dim,
|
207 |
-
nhead=self.num_head,
|
208 |
-
dim_feedforward=self.model_dim * 4,
|
209 |
-
dropout=0.1,
|
210 |
-
batch_first=True,
|
211 |
-
norm_first=norm_first,
|
212 |
-
),
|
213 |
-
num_layers=self.num_layers,
|
214 |
-
norm=LayerNorm(self.model_dim) if norm_first else None,
|
215 |
-
)
|
216 |
-
|
217 |
-
self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
|
218 |
-
self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
|
219 |
-
|
220 |
-
self.ar_accuracy_metric = MulticlassAccuracy(
|
221 |
-
self.vocab_size,
|
222 |
-
top_k=top_k,
|
223 |
-
average="micro",
|
224 |
-
multidim_average="global",
|
225 |
-
ignore_index=self.EOS,
|
226 |
-
)
|
227 |
-
|
228 |
-
blocks = []
|
229 |
-
|
230 |
-
for i in range(self.num_layers):
|
231 |
-
layer = self.h.layers[i]
|
232 |
-
t2smlp = T2SMLP(
|
233 |
-
layer.linear1.weight,
|
234 |
-
layer.linear1.bias,
|
235 |
-
layer.linear2.weight,
|
236 |
-
layer.linear2.bias
|
237 |
-
)
|
238 |
-
# (layer.self_attn.in_proj_weight, layer.self_attn.in_proj_bias)
|
239 |
-
block = T2SBlock(
|
240 |
-
self.num_head,
|
241 |
-
self.model_dim,
|
242 |
-
t2smlp,
|
243 |
-
layer.self_attn.in_proj_weight,
|
244 |
-
layer.self_attn.in_proj_bias,
|
245 |
-
layer.self_attn.out_proj.weight,
|
246 |
-
layer.self_attn.out_proj.bias,
|
247 |
-
layer.norm1.weight,
|
248 |
-
layer.norm1.bias,
|
249 |
-
layer.norm1.eps,
|
250 |
-
layer.norm2.weight,
|
251 |
-
layer.norm2.bias,
|
252 |
-
layer.norm2.eps
|
253 |
-
)
|
254 |
-
|
255 |
-
blocks.append(block)
|
256 |
-
|
257 |
-
self.t2s_transformer = T2STransformer(self.num_layers, blocks)
|
258 |
-
|
259 |
-
def make_input_data(self, x, x_lens, y, y_lens, bert_feature):
|
260 |
-
x = self.ar_text_embedding(x)
|
261 |
-
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
262 |
-
x = self.ar_text_position(x)
|
263 |
-
x_mask = make_pad_mask(x_lens)
|
264 |
-
|
265 |
-
y_mask = make_pad_mask(y_lens)
|
266 |
-
y_mask_int = y_mask.type(torch.int64)
|
267 |
-
codes = y.type(torch.int64) * (1 - y_mask_int)
|
268 |
-
|
269 |
-
# Training
|
270 |
-
# AR Decoder
|
271 |
-
y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
|
272 |
-
x_len = x_lens.max()
|
273 |
-
y_len = y_lens.max()
|
274 |
-
y_emb = self.ar_audio_embedding(y)
|
275 |
-
y_pos = self.ar_audio_position(y_emb)
|
276 |
-
|
277 |
-
xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
|
278 |
-
|
279 |
-
ar_xy_padding_mask = xy_padding_mask
|
280 |
-
|
281 |
-
x_attn_mask = F.pad(
|
282 |
-
torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
|
283 |
-
(0, y_len),
|
284 |
-
value=True,
|
285 |
-
)
|
286 |
-
|
287 |
-
y_attn_mask = F.pad(
|
288 |
-
torch.triu(
|
289 |
-
torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
|
290 |
-
diagonal=1,
|
291 |
-
),
|
292 |
-
(x_len, 0),
|
293 |
-
value=False,
|
294 |
-
)
|
295 |
-
|
296 |
-
xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
|
297 |
-
bsz, src_len = x.shape[0], x_len + y_len
|
298 |
-
_xy_padding_mask = (
|
299 |
-
ar_xy_padding_mask.view(bsz, 1, 1, src_len)
|
300 |
-
.expand(-1, self.num_head, -1, -1)
|
301 |
-
.reshape(bsz * self.num_head, 1, src_len)
|
302 |
-
)
|
303 |
-
xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
|
304 |
-
new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
|
305 |
-
new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
|
306 |
-
xy_attn_mask = new_attn_mask
|
307 |
-
# x 和完整的 y 一次性输入模型
|
308 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
309 |
-
|
310 |
-
return xy_pos, xy_attn_mask, targets
|
311 |
-
|
312 |
-
def forward(self, x, x_lens, y, y_lens, bert_feature):
|
313 |
-
"""
|
314 |
-
x: phoneme_ids
|
315 |
-
y: semantic_ids
|
316 |
-
"""
|
317 |
-
|
318 |
-
reject_y, reject_y_lens = make_reject_y(y, y_lens)
|
319 |
-
|
320 |
-
xy_pos, xy_attn_mask, targets = self.make_input_data(x, x_lens, y, y_lens, bert_feature)
|
321 |
-
|
322 |
-
xy_dec, _ = self.h(
|
323 |
-
(xy_pos, None),
|
324 |
-
mask=xy_attn_mask,
|
325 |
-
)
|
326 |
-
x_len = x_lens.max()
|
327 |
-
logits = self.ar_predict_layer(xy_dec[:, x_len:])
|
328 |
-
|
329 |
-
###### DPO #############
|
330 |
-
reject_xy_pos, reject_xy_attn_mask, reject_targets = self.make_input_data(x, x_lens, reject_y, reject_y_lens, bert_feature)
|
331 |
-
|
332 |
-
reject_xy_dec, _ = self.h(
|
333 |
-
(reject_xy_pos, None),
|
334 |
-
mask=reject_xy_attn_mask,
|
335 |
-
)
|
336 |
-
x_len = x_lens.max()
|
337 |
-
reject_logits = self.ar_predict_layer(reject_xy_dec[:, x_len:])
|
338 |
-
|
339 |
-
# loss
|
340 |
-
# from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
|
341 |
-
|
342 |
-
loss_1 = F.cross_entropy(logits.permute(0, 2, 1), targets, reduction="sum")
|
343 |
-
acc = self.ar_accuracy_metric(logits.permute(0, 2, 1).detach(), targets).item()
|
344 |
-
|
345 |
-
A_logits, R_logits = get_batch_logps(logits, reject_logits, targets, reject_targets)
|
346 |
-
loss_2, _, _ = dpo_loss(A_logits, R_logits, 0, 0, 0.2, reference_free=True)
|
347 |
-
|
348 |
-
loss = loss_1 + loss_2
|
349 |
-
|
350 |
-
return loss, acc
|
351 |
-
|
352 |
-
def forward_old(self, x, x_lens, y, y_lens, bert_feature):
|
353 |
-
"""
|
354 |
-
x: phoneme_ids
|
355 |
-
y: semantic_ids
|
356 |
-
"""
|
357 |
-
x = self.ar_text_embedding(x)
|
358 |
-
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
359 |
-
x = self.ar_text_position(x)
|
360 |
-
x_mask = make_pad_mask(x_lens)
|
361 |
-
|
362 |
-
y_mask = make_pad_mask(y_lens)
|
363 |
-
y_mask_int = y_mask.type(torch.int64)
|
364 |
-
codes = y.type(torch.int64) * (1 - y_mask_int)
|
365 |
-
|
366 |
-
# Training
|
367 |
-
# AR Decoder
|
368 |
-
y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
|
369 |
-
x_len = x_lens.max()
|
370 |
-
y_len = y_lens.max()
|
371 |
-
y_emb = self.ar_audio_embedding(y)
|
372 |
-
y_pos = self.ar_audio_position(y_emb)
|
373 |
-
|
374 |
-
xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
|
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 |
-
y_attn_mask = F.pad(
|
383 |
-
torch.triu(
|
384 |
-
torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
|
385 |
-
diagonal=1,
|
386 |
-
),
|
387 |
-
(x_len, 0),
|
388 |
-
value=False,
|
389 |
-
)
|
390 |
-
xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
|
391 |
-
bsz, src_len = x.shape[0], x_len + y_len
|
392 |
-
_xy_padding_mask = (
|
393 |
-
ar_xy_padding_mask.view(bsz, 1, 1, src_len)
|
394 |
-
.expand(-1, self.num_head, -1, -1)
|
395 |
-
.reshape(bsz * self.num_head, 1, src_len)
|
396 |
-
)
|
397 |
-
xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
|
398 |
-
new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
|
399 |
-
new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
|
400 |
-
xy_attn_mask = new_attn_mask
|
401 |
-
# x 和完整的 y 一次性输入模型
|
402 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
403 |
-
xy_dec, _ = self.h(
|
404 |
-
(xy_pos, None),
|
405 |
-
mask=xy_attn_mask,
|
406 |
-
)
|
407 |
-
logits = self.ar_predict_layer(xy_dec[:, x_len:]).permute(0, 2, 1)
|
408 |
-
# loss
|
409 |
-
# from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
|
410 |
-
loss = F.cross_entropy(logits, targets, reduction="sum")
|
411 |
-
acc = self.ar_accuracy_metric(logits.detach(), targets).item()
|
412 |
-
return loss, acc
|
413 |
-
|
414 |
-
# 需要看下这个函数和 forward 的区别以及没有 semantic 的时候 prompts 输入什么
|
415 |
-
def infer(
|
416 |
-
self,
|
417 |
-
x,
|
418 |
-
x_lens,
|
419 |
-
prompts,
|
420 |
-
bert_feature,
|
421 |
-
top_k: int = -100,
|
422 |
-
early_stop_num: int = -1,
|
423 |
-
temperature: float = 1.0,
|
424 |
-
):
|
425 |
-
x = self.ar_text_embedding(x)
|
426 |
-
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
427 |
-
x = self.ar_text_position(x)
|
428 |
-
|
429 |
-
# AR Decoder
|
430 |
-
y = prompts
|
431 |
-
prefix_len = y.shape[1]
|
432 |
-
x_len = x.shape[1]
|
433 |
-
x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
|
434 |
-
stop = False
|
435 |
-
for _ in tqdm(range(1500)):
|
436 |
-
y_emb = self.ar_audio_embedding(y)
|
437 |
-
y_pos = self.ar_audio_position(y_emb)
|
438 |
-
# x 和逐渐增长的 y 一起输入给模型
|
439 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
440 |
-
y_len = y.shape[1]
|
441 |
-
x_attn_mask_pad = F.pad(
|
442 |
-
x_attn_mask,
|
443 |
-
(0, y_len),
|
444 |
-
value=True,
|
445 |
-
)
|
446 |
-
y_attn_mask = F.pad(
|
447 |
-
torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
|
448 |
-
(x_len, 0),
|
449 |
-
value=False,
|
450 |
-
)
|
451 |
-
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0).to(
|
452 |
-
y.device
|
453 |
-
)
|
454 |
-
|
455 |
-
xy_dec, _ = self.h(
|
456 |
-
(xy_pos, None),
|
457 |
-
mask=xy_attn_mask,
|
458 |
-
)
|
459 |
-
logits = self.ar_predict_layer(xy_dec[:, -1])
|
460 |
-
samples = topk_sampling(
|
461 |
-
logits, top_k=top_k, top_p=1.0, temperature=temperature
|
462 |
-
)
|
463 |
-
|
464 |
-
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
465 |
-
print("use early stop num:", early_stop_num)
|
466 |
-
stop = True
|
467 |
-
|
468 |
-
if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
|
469 |
-
# print(torch.argmax(logits, dim=-1)[0] == self.EOS, samples[0, 0] == self.EOS)
|
470 |
-
stop = True
|
471 |
-
if stop:
|
472 |
-
if prompts.shape[1] == y.shape[1]:
|
473 |
-
y = torch.concat([y, torch.zeros_like(samples)], dim=1)
|
474 |
-
print("bad zero prediction")
|
475 |
-
print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
|
476 |
-
break
|
477 |
-
# 本次生成的 semantic_ids 和之前的 y 构成新的 y
|
478 |
-
# print(samples.shape)#[1,1]#第一个1是bs
|
479 |
-
# import os
|
480 |
-
# os._exit(2333)
|
481 |
-
y = torch.concat([y, samples], dim=1)
|
482 |
-
return y
|
483 |
-
|
484 |
-
def pad_y_eos(self, y, y_mask_int, eos_id):
|
485 |
-
targets = F.pad(y, (0, 1), value=0) + eos_id * F.pad(
|
486 |
-
y_mask_int, (0, 1), value=1
|
487 |
-
)
|
488 |
-
# 错位
|
489 |
-
return targets[:, :-1], targets[:, 1:]
|
490 |
-
|
491 |
-
def infer_panel(
|
492 |
-
self,
|
493 |
-
x, #####全部文本token
|
494 |
-
x_lens,
|
495 |
-
prompts, ####参考音频token
|
496 |
-
bert_feature,
|
497 |
-
top_k: int = -100,
|
498 |
-
top_p: int = 100,
|
499 |
-
early_stop_num: int = -1,
|
500 |
-
temperature: float = 1.0,
|
501 |
-
):
|
502 |
-
x = self.ar_text_embedding(x)
|
503 |
-
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
504 |
-
x = self.ar_text_position(x)
|
505 |
-
|
506 |
-
# AR Decoder
|
507 |
-
y = prompts
|
508 |
-
|
509 |
-
x_len = x.shape[1]
|
510 |
-
x_attn_mask = torch.zeros((x_len, x_len), dtype=torch.bool)
|
511 |
-
stop = False
|
512 |
-
# print(1111111,self.num_layers)
|
513 |
-
|
514 |
-
k_cache = None
|
515 |
-
v_cache = None
|
516 |
-
################### first step ##########################
|
517 |
-
if y is not None:
|
518 |
-
y_emb = self.ar_audio_embedding(y)
|
519 |
-
y_len = y_emb.shape[1]
|
520 |
-
prefix_len = y.shape[1]
|
521 |
-
y_pos = self.ar_audio_position(y_emb)
|
522 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
523 |
-
ref_free = False
|
524 |
-
else:
|
525 |
-
y_emb = None
|
526 |
-
y_len = 0
|
527 |
-
prefix_len = 0
|
528 |
-
y_pos = None
|
529 |
-
xy_pos = x
|
530 |
-
y = torch.zeros(x.shape[0], 0, dtype=torch.int, device=x.device)
|
531 |
-
prompts = y
|
532 |
-
ref_free = True
|
533 |
-
|
534 |
-
x_attn_mask_pad = F.pad(
|
535 |
-
x_attn_mask,
|
536 |
-
(0, y_len), ###xx的纯0扩展到xx纯0+xy纯1,(x,x+y)
|
537 |
-
value=True,
|
538 |
-
)
|
539 |
-
y_attn_mask = F.pad( ###yy的右上1扩展到左边xy的0,(y,x+y)
|
540 |
-
torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
|
541 |
-
(x_len, 0),
|
542 |
-
value=False,
|
543 |
-
)
|
544 |
-
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0).to(
|
545 |
-
x.device
|
546 |
-
)
|
547 |
-
|
548 |
-
for idx in tqdm(range(1500)):
|
549 |
-
if xy_attn_mask is not None:
|
550 |
-
xy_dec, k_cache, v_cache = self.t2s_transformer.process_prompt(xy_pos, xy_attn_mask)
|
551 |
-
else:
|
552 |
-
xy_dec, k_cache, v_cache = self.t2s_transformer.decode_next_token(xy_pos, k_cache, v_cache)
|
553 |
-
|
554 |
-
logits = self.ar_predict_layer(
|
555 |
-
xy_dec[:, -1]
|
556 |
-
)
|
557 |
-
|
558 |
-
if idx == 0:
|
559 |
-
xy_attn_mask = None
|
560 |
-
logits = logits[:, :-1]
|
561 |
-
samples = sample(
|
562 |
-
logits[0], y, top_k=top_k, top_p=top_p, repetition_penalty=1.35, temperature=temperature
|
563 |
-
)[0].unsqueeze(0)
|
564 |
-
|
565 |
-
y = torch.concat([y, samples], dim=1)
|
566 |
-
|
567 |
-
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
568 |
-
print("use early stop num:", early_stop_num)
|
569 |
-
stop = True
|
570 |
-
|
571 |
-
if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
|
572 |
-
stop = True
|
573 |
-
if stop:
|
574 |
-
if y.shape[1] == 0:
|
575 |
-
y = torch.concat([y, torch.zeros_like(samples)], dim=1)
|
576 |
-
print("bad zero prediction")
|
577 |
-
print(f"T2S Decoding EOS [{prefix_len} -> {y.shape[1]}]")
|
578 |
-
break
|
579 |
-
|
580 |
-
####################### update next step ###################################
|
581 |
-
y_emb = self.ar_audio_embedding(y[:, -1:])
|
582 |
-
xy_pos = y_emb * self.ar_audio_position.x_scale + self.ar_audio_position.alpha * self.ar_audio_position.pe[:, y_len + idx].to(dtype=y_emb.dtype,device=y_emb.device)
|
583 |
-
|
584 |
-
if ref_free:
|
585 |
-
return y[:, :-1], 0
|
586 |
-
return y[:, :-1], idx - 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/models/t2s_model_abc.py
CHANGED
@@ -12,10 +12,10 @@ import torch.nn.functional as F
|
|
12 |
from torch.cuda.graphs import CUDAGraph
|
13 |
from torch.profiler import ProfilerAction, tensorboard_trace_handler
|
14 |
|
15 |
-
from AR.
|
16 |
SinePositionalEmbeddingNested as SinePositionalEmbedding,
|
17 |
)
|
18 |
-
from AR.
|
19 |
|
20 |
Tensor = torch.Tensor
|
21 |
|
|
|
12 |
from torch.cuda.graphs import CUDAGraph
|
13 |
from torch.profiler import ProfilerAction, tensorboard_trace_handler
|
14 |
|
15 |
+
from AR.models.embedding import (
|
16 |
SinePositionalEmbeddingNested as SinePositionalEmbedding,
|
17 |
)
|
18 |
+
from AR.models.embedding import TokenEmbedding
|
19 |
|
20 |
Tensor = torch.Tensor
|
21 |
|
AR/models/t2s_model_flash_attn.py
CHANGED
@@ -9,6 +9,10 @@ import torch
|
|
9 |
import torch.nn as nn
|
10 |
from tqdm import tqdm
|
11 |
|
|
|
|
|
|
|
|
|
12 |
from AR.models.structs import T2SRequest, T2SResult, T2SSession
|
13 |
from AR.models.t2s_model_abc import (
|
14 |
AttentionABC,
|
@@ -20,10 +24,6 @@ from AR.models.t2s_model_abc import (
|
|
20 |
TransformerBlockABC,
|
21 |
TransformerDecoderABC,
|
22 |
)
|
23 |
-
from AR.modules.embedding import (
|
24 |
-
SinePositionalEmbeddingNested as SinePositionalEmbedding,
|
25 |
-
)
|
26 |
-
from AR.modules.embedding import TokenEmbedding
|
27 |
|
28 |
Tensor = torch.Tensor
|
29 |
|
|
|
9 |
import torch.nn as nn
|
10 |
from tqdm import tqdm
|
11 |
|
12 |
+
from AR.models.embedding import (
|
13 |
+
SinePositionalEmbeddingNested as SinePositionalEmbedding,
|
14 |
+
)
|
15 |
+
from AR.models.embedding import TokenEmbedding
|
16 |
from AR.models.structs import T2SRequest, T2SResult, T2SSession
|
17 |
from AR.models.t2s_model_abc import (
|
18 |
AttentionABC,
|
|
|
24 |
TransformerBlockABC,
|
25 |
TransformerDecoderABC,
|
26 |
)
|
|
|
|
|
|
|
|
|
27 |
|
28 |
Tensor = torch.Tensor
|
29 |
|
AR/models/t2s_model_onnx.py
DELETED
@@ -1,338 +0,0 @@
|
|
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 tqdm import tqdm
|
5 |
-
|
6 |
-
from AR.modules.embedding_onnx import SinePositionalEmbedding
|
7 |
-
from AR.modules.embedding_onnx import TokenEmbedding
|
8 |
-
from AR.modules.transformer_onnx import LayerNorm
|
9 |
-
from AR.modules.transformer_onnx import TransformerEncoder
|
10 |
-
from AR.modules.transformer_onnx import TransformerEncoderLayer
|
11 |
-
from torch import nn
|
12 |
-
from torch.nn import functional as F
|
13 |
-
from torchmetrics.classification import MulticlassAccuracy
|
14 |
-
|
15 |
-
default_config = {
|
16 |
-
"embedding_dim": 512,
|
17 |
-
"hidden_dim": 512,
|
18 |
-
"num_head": 8,
|
19 |
-
"num_layers": 12,
|
20 |
-
"num_codebook": 8,
|
21 |
-
"p_dropout": 0.0,
|
22 |
-
"vocab_size": 1024 + 1,
|
23 |
-
"phoneme_vocab_size": 512,
|
24 |
-
"EOS": 1024,
|
25 |
-
}
|
26 |
-
|
27 |
-
inf_tensor_value = torch.FloatTensor([-float("Inf")]).float()
|
28 |
-
|
29 |
-
def logits_to_probs(
|
30 |
-
logits,
|
31 |
-
previous_tokens = None,
|
32 |
-
temperature: float = 1.0,
|
33 |
-
top_k = None,
|
34 |
-
top_p = None,
|
35 |
-
repetition_penalty: float = 1.0,
|
36 |
-
):
|
37 |
-
previous_tokens = previous_tokens.squeeze()
|
38 |
-
if previous_tokens is not None and repetition_penalty != 1.0:
|
39 |
-
previous_tokens = previous_tokens.long()
|
40 |
-
score = torch.gather(logits, dim=0, index=previous_tokens)
|
41 |
-
score = torch.where(
|
42 |
-
score < 0, score * repetition_penalty, score / repetition_penalty
|
43 |
-
)
|
44 |
-
logits.scatter_(dim=0, index=previous_tokens, src=score)
|
45 |
-
|
46 |
-
if top_p is not None and top_p < 1.0:
|
47 |
-
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
48 |
-
cum_probs = torch.cumsum(
|
49 |
-
torch.nn.functional.softmax(sorted_logits, dim=-1), dim=-1
|
50 |
-
)
|
51 |
-
sorted_indices_to_remove = cum_probs > top_p
|
52 |
-
sorted_indices_to_remove[0] = False # keep at least one option
|
53 |
-
indices_to_remove = sorted_indices_to_remove.scatter(
|
54 |
-
dim=0, index=sorted_indices, src=sorted_indices_to_remove
|
55 |
-
)
|
56 |
-
logits = logits.masked_fill(indices_to_remove, -float("Inf"))
|
57 |
-
|
58 |
-
logits = logits / max(temperature, 1e-5)
|
59 |
-
|
60 |
-
if top_k is not None:
|
61 |
-
v, _ = torch.topk(logits, top_k)
|
62 |
-
pivot = v.select(-1, -1).unsqueeze(-1)
|
63 |
-
logits = torch.where(logits < pivot, inf_tensor_value, logits)
|
64 |
-
|
65 |
-
probs = torch.nn.functional.softmax(logits, dim=-1)
|
66 |
-
return probs
|
67 |
-
|
68 |
-
|
69 |
-
def multinomial_sample_one_no_sync(
|
70 |
-
probs_sort
|
71 |
-
): # Does multinomial sampling without a cuda synchronization
|
72 |
-
q = torch.randn_like(probs_sort)
|
73 |
-
return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
|
74 |
-
|
75 |
-
|
76 |
-
def sample(
|
77 |
-
logits,
|
78 |
-
previous_tokens,
|
79 |
-
**sampling_kwargs,
|
80 |
-
):
|
81 |
-
probs = logits_to_probs(
|
82 |
-
logits=logits, previous_tokens=previous_tokens, **sampling_kwargs
|
83 |
-
)
|
84 |
-
idx_next = multinomial_sample_one_no_sync(probs)
|
85 |
-
return idx_next, probs
|
86 |
-
|
87 |
-
|
88 |
-
class OnnxEncoder(nn.Module):
|
89 |
-
def __init__(self, ar_text_embedding, bert_proj, ar_text_position):
|
90 |
-
super().__init__()
|
91 |
-
self.ar_text_embedding = ar_text_embedding
|
92 |
-
self.bert_proj = bert_proj
|
93 |
-
self.ar_text_position = ar_text_position
|
94 |
-
|
95 |
-
def forward(self, x, bert_feature):
|
96 |
-
x = self.ar_text_embedding(x)
|
97 |
-
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
98 |
-
return self.ar_text_position(x)
|
99 |
-
|
100 |
-
|
101 |
-
class T2SFirstStageDecoder(nn.Module):
|
102 |
-
def __init__(self, ar_audio_embedding, ar_audio_position, h, ar_predict_layer, loss_fct, ar_accuracy_metric,
|
103 |
-
top_k, early_stop_num, num_layers):
|
104 |
-
super().__init__()
|
105 |
-
self.ar_audio_embedding = ar_audio_embedding
|
106 |
-
self.ar_audio_position = ar_audio_position
|
107 |
-
self.h = h
|
108 |
-
self.ar_predict_layer = ar_predict_layer
|
109 |
-
self.loss_fct = loss_fct
|
110 |
-
self.ar_accuracy_metric = ar_accuracy_metric
|
111 |
-
self.top_k = top_k
|
112 |
-
self.early_stop_num = early_stop_num
|
113 |
-
self.num_layers = num_layers
|
114 |
-
|
115 |
-
def forward(self, x, prompt):
|
116 |
-
y = prompt
|
117 |
-
x_example = x[:,:,0] * 0.0
|
118 |
-
#N, 1, 512
|
119 |
-
cache = {
|
120 |
-
"all_stage": self.num_layers,
|
121 |
-
"k": None,
|
122 |
-
"v": None,
|
123 |
-
"y_emb": None,
|
124 |
-
"first_infer": 1,
|
125 |
-
"stage": 0,
|
126 |
-
}
|
127 |
-
|
128 |
-
y_emb = self.ar_audio_embedding(y)
|
129 |
-
|
130 |
-
cache["y_emb"] = y_emb
|
131 |
-
y_pos = self.ar_audio_position(y_emb)
|
132 |
-
|
133 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
134 |
-
|
135 |
-
y_example = y_pos[:,:,0] * 0.0
|
136 |
-
x_attn_mask = torch.matmul(x_example.transpose(0, 1) , x_example).bool()
|
137 |
-
y_attn_mask = torch.ones_like(torch.matmul(y_example.transpose(0, 1), y_example), dtype=torch.int64)
|
138 |
-
y_attn_mask = torch.cumsum(y_attn_mask, dim=1) - torch.cumsum(
|
139 |
-
torch.ones_like(y_example.transpose(0, 1), dtype=torch.int64), dim=0
|
140 |
-
)
|
141 |
-
y_attn_mask = y_attn_mask > 0
|
142 |
-
|
143 |
-
x_y_pad = torch.matmul(x_example.transpose(0, 1), y_example).bool()
|
144 |
-
y_x_pad = torch.matmul(y_example.transpose(0, 1), x_example).bool()
|
145 |
-
x_attn_mask_pad = torch.cat([x_attn_mask, torch.ones_like(x_y_pad)], dim=1)
|
146 |
-
y_attn_mask = torch.cat([y_x_pad, y_attn_mask], dim=1)
|
147 |
-
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
|
148 |
-
cache["k"] = torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))\
|
149 |
-
.unsqueeze(1).repeat(self.num_layers, 1, 1, 1)
|
150 |
-
cache["v"] = torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))\
|
151 |
-
.unsqueeze(1).repeat(self.num_layers, 1, 1, 1)
|
152 |
-
|
153 |
-
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
154 |
-
logits = self.ar_predict_layer(xy_dec[:, -1])
|
155 |
-
samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
156 |
-
|
157 |
-
y = torch.concat([y, samples], dim=1)
|
158 |
-
|
159 |
-
return y, cache["k"], cache["v"], cache["y_emb"], x_example
|
160 |
-
|
161 |
-
|
162 |
-
class T2SStageDecoder(nn.Module):
|
163 |
-
def __init__(self, ar_audio_embedding, ar_audio_position, h, ar_predict_layer, loss_fct, ar_accuracy_metric,
|
164 |
-
top_k, early_stop_num, num_layers):
|
165 |
-
super().__init__()
|
166 |
-
self.ar_audio_embedding = ar_audio_embedding
|
167 |
-
self.ar_audio_position = ar_audio_position
|
168 |
-
self.h = h
|
169 |
-
self.ar_predict_layer = ar_predict_layer
|
170 |
-
self.loss_fct = loss_fct
|
171 |
-
self.ar_accuracy_metric = ar_accuracy_metric
|
172 |
-
self.top_k = top_k
|
173 |
-
self.early_stop_num = early_stop_num
|
174 |
-
self.num_layers = num_layers
|
175 |
-
|
176 |
-
def forward(self, y, k, v, y_emb, x_example):
|
177 |
-
cache = {
|
178 |
-
"all_stage": self.num_layers,
|
179 |
-
"k": torch.nn.functional.pad(k, (0, 0, 0, 0, 0, 1)),
|
180 |
-
"v": torch.nn.functional.pad(v, (0, 0, 0, 0, 0, 1)),
|
181 |
-
"y_emb": y_emb,
|
182 |
-
"first_infer": 0,
|
183 |
-
"stage": 0,
|
184 |
-
}
|
185 |
-
|
186 |
-
y_emb = torch.cat(
|
187 |
-
[cache["y_emb"], self.ar_audio_embedding(y[:, -1:])], 1
|
188 |
-
)
|
189 |
-
cache["y_emb"] = y_emb
|
190 |
-
y_pos = self.ar_audio_position(y_emb)
|
191 |
-
|
192 |
-
xy_pos = y_pos[:, -1:]
|
193 |
-
|
194 |
-
y_example = y_pos[:,:,0] * 0.0
|
195 |
-
|
196 |
-
xy_attn_mask = torch.cat([x_example, y_example], dim=1)
|
197 |
-
xy_attn_mask = torch.zeros_like(xy_attn_mask, dtype=torch.bool)
|
198 |
-
|
199 |
-
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
200 |
-
logits = self.ar_predict_layer(xy_dec[:, -1])
|
201 |
-
samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
202 |
-
|
203 |
-
y = torch.concat([y, samples], dim=1)
|
204 |
-
|
205 |
-
return y, cache["k"], cache["v"], cache["y_emb"], logits, samples
|
206 |
-
|
207 |
-
|
208 |
-
class Text2SemanticDecoder(nn.Module):
|
209 |
-
def __init__(self, config, norm_first=False, top_k=3):
|
210 |
-
super(Text2SemanticDecoder, self).__init__()
|
211 |
-
self.model_dim = config["model"]["hidden_dim"]
|
212 |
-
self.embedding_dim = config["model"]["embedding_dim"]
|
213 |
-
self.num_head = config["model"]["head"]
|
214 |
-
self.num_layers = config["model"]["n_layer"]
|
215 |
-
self.norm_first = norm_first
|
216 |
-
self.vocab_size = config["model"]["vocab_size"]
|
217 |
-
self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
|
218 |
-
self.p_dropout = float(config["model"]["dropout"])
|
219 |
-
self.EOS = config["model"]["EOS"]
|
220 |
-
self.norm_first = norm_first
|
221 |
-
assert self.EOS == self.vocab_size - 1
|
222 |
-
self.bert_proj = nn.Linear(1024, self.embedding_dim)
|
223 |
-
self.ar_text_embedding = TokenEmbedding(self.embedding_dim, self.phoneme_vocab_size, self.p_dropout)
|
224 |
-
self.ar_text_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
|
225 |
-
self.ar_audio_embedding = TokenEmbedding(self.embedding_dim, self.vocab_size, self.p_dropout)
|
226 |
-
self.ar_audio_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
|
227 |
-
self.h = TransformerEncoder(
|
228 |
-
TransformerEncoderLayer(
|
229 |
-
d_model=self.model_dim,
|
230 |
-
nhead=self.num_head,
|
231 |
-
dim_feedforward=self.model_dim * 4,
|
232 |
-
dropout=0.1,
|
233 |
-
batch_first=True,
|
234 |
-
norm_first=norm_first,
|
235 |
-
),
|
236 |
-
num_layers=self.num_layers,
|
237 |
-
norm=LayerNorm(self.model_dim) if norm_first else None,
|
238 |
-
)
|
239 |
-
self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
|
240 |
-
self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
|
241 |
-
self.ar_accuracy_metric = MulticlassAccuracy(
|
242 |
-
self.vocab_size,
|
243 |
-
top_k=top_k,
|
244 |
-
average="micro",
|
245 |
-
multidim_average="global",
|
246 |
-
ignore_index=self.EOS,
|
247 |
-
)
|
248 |
-
self.top_k = torch.LongTensor([1])
|
249 |
-
self.early_stop_num = torch.LongTensor([-1])
|
250 |
-
|
251 |
-
def init_onnx(self):
|
252 |
-
self.onnx_encoder = OnnxEncoder(self.ar_text_embedding, self.bert_proj, self.ar_text_position)
|
253 |
-
self.first_stage_decoder = T2SFirstStageDecoder(self.ar_audio_embedding, self.ar_audio_position, self.h,
|
254 |
-
self.ar_predict_layer, self.loss_fct, self.ar_accuracy_metric, self.top_k, self.early_stop_num,
|
255 |
-
self.num_layers)
|
256 |
-
self.stage_decoder = T2SStageDecoder(self.ar_audio_embedding, self.ar_audio_position, self.h,
|
257 |
-
self.ar_predict_layer, self.loss_fct, self.ar_accuracy_metric, self.top_k, self.early_stop_num,
|
258 |
-
self.num_layers)
|
259 |
-
|
260 |
-
def forward(self, x, prompts, bert_feature):
|
261 |
-
early_stop_num = self.early_stop_num
|
262 |
-
prefix_len = prompts.shape[1]
|
263 |
-
|
264 |
-
x = self.onnx_encoder(x, bert_feature)
|
265 |
-
y, k, v, y_emb, stage, x_example = self.first_stage_decoder(x, prompts)
|
266 |
-
|
267 |
-
stop = False
|
268 |
-
for idx in range(1, 1500):
|
269 |
-
enco = self.stage_decoder(y, k, v, y_emb, stage, x_example)
|
270 |
-
y, k, v, y_emb, stage, logits, samples = enco
|
271 |
-
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
272 |
-
stop = True
|
273 |
-
if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
|
274 |
-
stop = True
|
275 |
-
if stop:
|
276 |
-
break
|
277 |
-
y[0, -1] = 0
|
278 |
-
return y, idx
|
279 |
-
|
280 |
-
def infer(self, x, prompts, bert_feature):
|
281 |
-
top_k = self.top_k
|
282 |
-
early_stop_num = self.early_stop_num
|
283 |
-
|
284 |
-
x = self.onnx_encoder(x, bert_feature)
|
285 |
-
|
286 |
-
y = prompts
|
287 |
-
prefix_len = y.shape[1]
|
288 |
-
x_len = x.shape[1]
|
289 |
-
x_example = x[:,:,0] * 0.0
|
290 |
-
x_attn_mask = torch.matmul(x_example.transpose(0, 1), x_example)
|
291 |
-
x_attn_mask = torch.zeros_like(x_attn_mask, dtype=torch.bool)
|
292 |
-
|
293 |
-
stop = False
|
294 |
-
cache = {
|
295 |
-
"all_stage": self.num_layers,
|
296 |
-
"k": [None] * self.num_layers,
|
297 |
-
"v": [None] * self.num_layers,
|
298 |
-
"y_emb": None,
|
299 |
-
"first_infer": 1,
|
300 |
-
"stage": 0,
|
301 |
-
}
|
302 |
-
for idx in range(1500):
|
303 |
-
if cache["first_infer"] == 1:
|
304 |
-
y_emb = self.ar_audio_embedding(y)
|
305 |
-
else:
|
306 |
-
y_emb = torch.cat(
|
307 |
-
[cache["y_emb"], self.ar_audio_embedding(y[:, -1:])], 1
|
308 |
-
)
|
309 |
-
cache["y_emb"] = y_emb
|
310 |
-
y_pos = self.ar_audio_position(y_emb)
|
311 |
-
if cache["first_infer"] == 1:
|
312 |
-
xy_pos = torch.concat([x, y_pos], dim=1)
|
313 |
-
else:
|
314 |
-
xy_pos = y_pos[:, -1:]
|
315 |
-
y_len = y_pos.shape[1]
|
316 |
-
if cache["first_infer"] == 1:
|
317 |
-
x_attn_mask_pad = F.pad(x_attn_mask, (0, y_len), value=True)
|
318 |
-
y_attn_mask = F.pad(
|
319 |
-
torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
|
320 |
-
(x_len, 0), value=False
|
321 |
-
)
|
322 |
-
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
|
323 |
-
else:
|
324 |
-
xy_attn_mask = torch.zeros((1, x_len + y_len), dtype=torch.bool)
|
325 |
-
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
326 |
-
logits = self.ar_predict_layer(xy_dec[:, -1])
|
327 |
-
samples = sample(logits[0], y, top_k=top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
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 |
-
if prompts.shape[1] == y.shape[1]:
|
334 |
-
y = torch.concat([y, torch.zeros_like(samples)], dim=1)
|
335 |
-
break
|
336 |
-
y = torch.concat([y, samples], dim=1)
|
337 |
-
cache["first_infer"] = 0
|
338 |
-
return y, idx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/__init__.py
DELETED
File without changes
|
AR/modules/activation.py
DELETED
@@ -1,428 +0,0 @@
|
|
1 |
-
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
|
2 |
-
from typing import Optional
|
3 |
-
from typing import Tuple
|
4 |
-
import torch
|
5 |
-
from torch import Tensor
|
6 |
-
from torch.nn import Linear
|
7 |
-
from torch.nn import Module
|
8 |
-
from torch.nn.init import constant_
|
9 |
-
from torch.nn.init import xavier_normal_
|
10 |
-
from torch.nn.init import xavier_uniform_
|
11 |
-
from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
|
12 |
-
from torch.nn.parameter import Parameter
|
13 |
-
|
14 |
-
from torch.nn import functional as F
|
15 |
-
from AR.modules.patched_mha_with_cache import multi_head_attention_forward_patched
|
16 |
-
|
17 |
-
F.multi_head_attention_forward = multi_head_attention_forward_patched
|
18 |
-
|
19 |
-
|
20 |
-
class MultiheadAttention(Module):
|
21 |
-
r"""Allows the model to jointly attend to information
|
22 |
-
from different representation subspaces as described in the paper:
|
23 |
-
`Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
|
24 |
-
|
25 |
-
Multi-Head Attention is defined as:
|
26 |
-
|
27 |
-
.. math::
|
28 |
-
\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
|
29 |
-
|
30 |
-
where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
|
31 |
-
|
32 |
-
``forward()`` will use a special optimized implementation if all of the following
|
33 |
-
conditions are met:
|
34 |
-
|
35 |
-
- self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor. This
|
36 |
-
restriction will be loosened in the future.)
|
37 |
-
- Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
|
38 |
-
- training is disabled (using ``.eval()``)
|
39 |
-
- dropout is 0
|
40 |
-
- ``add_bias_kv`` is ``False``
|
41 |
-
- ``add_zero_attn`` is ``False``
|
42 |
-
- ``batch_first`` is ``True`` and the input is batched
|
43 |
-
- ``kdim`` and ``vdim`` are equal to ``embed_dim``
|
44 |
-
- at most one of ``key_padding_mask`` or ``attn_mask`` is passed
|
45 |
-
- if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
|
46 |
-
nor ``attn_mask`` is passed
|
47 |
-
|
48 |
-
If the optimized implementation is in use, a
|
49 |
-
`NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
|
50 |
-
``query``/``key``/``value`` to represent padding more efficiently than using a
|
51 |
-
padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
|
52 |
-
will be returned, and an additional speedup proportional to the fraction of the input
|
53 |
-
that is padding can be expected.
|
54 |
-
|
55 |
-
Args:
|
56 |
-
embed_dim: Total dimension of the model.
|
57 |
-
num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
|
58 |
-
across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
|
59 |
-
dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
|
60 |
-
bias: If specified, adds bias to input / output projection layers. Default: ``True``.
|
61 |
-
add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
|
62 |
-
add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
|
63 |
-
Default: ``False``.
|
64 |
-
kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
|
65 |
-
vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
|
66 |
-
batch_first: If ``True``, then the input and output tensors are provided
|
67 |
-
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
68 |
-
|
69 |
-
Examples::
|
70 |
-
|
71 |
-
>>> # xdoctest: +SKIP
|
72 |
-
>>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
|
73 |
-
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
|
74 |
-
|
75 |
-
"""
|
76 |
-
__constants__ = ["batch_first"]
|
77 |
-
bias_k: Optional[torch.Tensor]
|
78 |
-
bias_v: Optional[torch.Tensor]
|
79 |
-
|
80 |
-
def __init__(
|
81 |
-
self,
|
82 |
-
embed_dim,
|
83 |
-
num_heads,
|
84 |
-
dropout=0.0,
|
85 |
-
bias=True,
|
86 |
-
add_bias_kv=False,
|
87 |
-
add_zero_attn=False,
|
88 |
-
kdim=None,
|
89 |
-
vdim=None,
|
90 |
-
batch_first=False,
|
91 |
-
linear1_cls=Linear,
|
92 |
-
linear2_cls=Linear,
|
93 |
-
device=None,
|
94 |
-
dtype=None,
|
95 |
-
) -> None:
|
96 |
-
factory_kwargs = {"device": device, "dtype": dtype}
|
97 |
-
super(MultiheadAttention, self).__init__()
|
98 |
-
self.embed_dim = embed_dim
|
99 |
-
self.kdim = kdim if kdim is not None else embed_dim
|
100 |
-
self.vdim = vdim if vdim is not None else embed_dim
|
101 |
-
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
102 |
-
|
103 |
-
self.num_heads = num_heads
|
104 |
-
self.dropout = dropout
|
105 |
-
self.batch_first = batch_first
|
106 |
-
self.head_dim = embed_dim // num_heads
|
107 |
-
assert (
|
108 |
-
self.head_dim * num_heads == self.embed_dim
|
109 |
-
), "embed_dim must be divisible by num_heads"
|
110 |
-
|
111 |
-
if add_bias_kv:
|
112 |
-
self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
113 |
-
self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
114 |
-
else:
|
115 |
-
self.bias_k = self.bias_v = None
|
116 |
-
|
117 |
-
if linear1_cls == Linear:
|
118 |
-
if not self._qkv_same_embed_dim:
|
119 |
-
self.q_proj_weight = Parameter(
|
120 |
-
torch.empty((embed_dim, embed_dim), **factory_kwargs)
|
121 |
-
)
|
122 |
-
self.k_proj_weight = Parameter(
|
123 |
-
torch.empty((embed_dim, self.kdim), **factory_kwargs)
|
124 |
-
)
|
125 |
-
self.v_proj_weight = Parameter(
|
126 |
-
torch.empty((embed_dim, self.vdim), **factory_kwargs)
|
127 |
-
)
|
128 |
-
self.register_parameter("in_proj_weight", None)
|
129 |
-
else:
|
130 |
-
self.in_proj_weight = Parameter(
|
131 |
-
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
|
132 |
-
)
|
133 |
-
self.register_parameter("q_proj_weight", None)
|
134 |
-
self.register_parameter("k_proj_weight", None)
|
135 |
-
self.register_parameter("v_proj_weight", None)
|
136 |
-
|
137 |
-
if bias:
|
138 |
-
self.in_proj_bias = Parameter(
|
139 |
-
torch.empty(3 * embed_dim, **factory_kwargs)
|
140 |
-
)
|
141 |
-
else:
|
142 |
-
self.register_parameter("in_proj_bias", None)
|
143 |
-
self.out_proj = NonDynamicallyQuantizableLinear(
|
144 |
-
embed_dim, embed_dim, bias=bias, **factory_kwargs
|
145 |
-
)
|
146 |
-
|
147 |
-
self._reset_parameters()
|
148 |
-
else:
|
149 |
-
if not self._qkv_same_embed_dim:
|
150 |
-
raise NotImplementedError
|
151 |
-
else:
|
152 |
-
self.in_proj_linear = linear1_cls(
|
153 |
-
embed_dim, 3 * embed_dim, bias=bias, **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, embed_dim, bias=bias, **factory_kwargs
|
168 |
-
)
|
169 |
-
|
170 |
-
if self.bias_k is not None:
|
171 |
-
xavier_normal_(self.bias_k)
|
172 |
-
if self.bias_v is not None:
|
173 |
-
xavier_normal_(self.bias_v)
|
174 |
-
|
175 |
-
self.add_zero_attn = add_zero_attn
|
176 |
-
|
177 |
-
def _reset_parameters(self):
|
178 |
-
if self._qkv_same_embed_dim:
|
179 |
-
xavier_uniform_(self.in_proj_weight)
|
180 |
-
else:
|
181 |
-
xavier_uniform_(self.q_proj_weight)
|
182 |
-
xavier_uniform_(self.k_proj_weight)
|
183 |
-
xavier_uniform_(self.v_proj_weight)
|
184 |
-
|
185 |
-
if self.in_proj_bias is not None:
|
186 |
-
constant_(self.in_proj_bias, 0.0)
|
187 |
-
constant_(self.out_proj.bias, 0.0)
|
188 |
-
|
189 |
-
if self.bias_k is not None:
|
190 |
-
xavier_normal_(self.bias_k)
|
191 |
-
if self.bias_v is not None:
|
192 |
-
xavier_normal_(self.bias_v)
|
193 |
-
|
194 |
-
def __setstate__(self, state):
|
195 |
-
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
|
196 |
-
if "_qkv_same_embed_dim" not in state:
|
197 |
-
state["_qkv_same_embed_dim"] = True
|
198 |
-
|
199 |
-
super(MultiheadAttention, self).__setstate__(state)
|
200 |
-
|
201 |
-
def forward(
|
202 |
-
self,
|
203 |
-
query: Tensor,
|
204 |
-
key: Tensor,
|
205 |
-
value: Tensor,
|
206 |
-
key_padding_mask: Optional[Tensor] = None,
|
207 |
-
need_weights: bool = True,
|
208 |
-
attn_mask: Optional[Tensor] = None,
|
209 |
-
average_attn_weights: bool = True,
|
210 |
-
cache=None,
|
211 |
-
) -> Tuple[Tensor, Optional[Tensor]]:
|
212 |
-
r"""
|
213 |
-
Args:
|
214 |
-
query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
|
215 |
-
or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
|
216 |
-
:math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
|
217 |
-
Queries are compared against key-value pairs to produce the output.
|
218 |
-
See "Attention Is All You Need" for more details.
|
219 |
-
key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
|
220 |
-
or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
|
221 |
-
:math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
|
222 |
-
See "Attention Is All You Need" for more details.
|
223 |
-
value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
|
224 |
-
``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
|
225 |
-
sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
|
226 |
-
See "Attention Is All You Need" for more details.
|
227 |
-
key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
|
228 |
-
to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
|
229 |
-
Binary and byte masks are supported.
|
230 |
-
For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
|
231 |
-
the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
|
232 |
-
need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
|
233 |
-
Default: ``True``.
|
234 |
-
attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
|
235 |
-
:math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
|
236 |
-
:math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
|
237 |
-
broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
|
238 |
-
Binary, byte, and float masks are supported. For a binary mask, a ``True`` value indicates that the
|
239 |
-
corresponding position is not allowed to attend. For a byte mask, a non-zero value indicates that the
|
240 |
-
corresponding position is not allowed to attend. For a float mask, the mask values will be added to
|
241 |
-
the attention weight.
|
242 |
-
average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
|
243 |
-
heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
|
244 |
-
effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
|
245 |
-
|
246 |
-
Outputs:
|
247 |
-
- **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
|
248 |
-
:math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
|
249 |
-
where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
|
250 |
-
embedding dimension ``embed_dim``.
|
251 |
-
- **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
|
252 |
-
returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
|
253 |
-
:math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
|
254 |
-
:math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
255 |
-
head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
|
256 |
-
|
257 |
-
.. note::
|
258 |
-
`batch_first` argument is ignored for unbatched inputs.
|
259 |
-
"""
|
260 |
-
is_batched = query.dim() == 3
|
261 |
-
if key_padding_mask is not None:
|
262 |
-
_kpm_dtype = key_padding_mask.dtype
|
263 |
-
if _kpm_dtype != torch.bool and not torch.is_floating_point(
|
264 |
-
key_padding_mask
|
265 |
-
):
|
266 |
-
raise AssertionError(
|
267 |
-
"only bool and floating types of key_padding_mask are supported"
|
268 |
-
)
|
269 |
-
why_not_fast_path = ""
|
270 |
-
if not is_batched:
|
271 |
-
why_not_fast_path = (
|
272 |
-
f"input not batched; expected query.dim() of 3 but got {query.dim()}"
|
273 |
-
)
|
274 |
-
elif query is not key or key is not value:
|
275 |
-
# When lifting this restriction, don't forget to either
|
276 |
-
# enforce that the dtypes all match or test cases where
|
277 |
-
# they don't!
|
278 |
-
why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
|
279 |
-
elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
|
280 |
-
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
|
281 |
-
elif (
|
282 |
-
self.in_proj_weight is not None and query.dtype != self.in_proj_weight.dtype
|
283 |
-
):
|
284 |
-
# this case will fail anyway, but at least they'll get a useful error message.
|
285 |
-
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
|
286 |
-
elif self.training:
|
287 |
-
why_not_fast_path = "training is enabled"
|
288 |
-
elif not self.batch_first:
|
289 |
-
why_not_fast_path = "batch_first was not True"
|
290 |
-
elif self.bias_k is not None:
|
291 |
-
why_not_fast_path = "self.bias_k was not None"
|
292 |
-
elif self.bias_v is not None:
|
293 |
-
why_not_fast_path = "self.bias_v was not None"
|
294 |
-
elif self.dropout:
|
295 |
-
why_not_fast_path = f"dropout was {self.dropout}, required zero"
|
296 |
-
elif self.add_zero_attn:
|
297 |
-
why_not_fast_path = "add_zero_attn was enabled"
|
298 |
-
elif not self._qkv_same_embed_dim:
|
299 |
-
why_not_fast_path = "_qkv_same_embed_dim was not True"
|
300 |
-
elif attn_mask is not None:
|
301 |
-
why_not_fast_path = "attn_mask was not None"
|
302 |
-
elif query.is_nested and key_padding_mask is not None:
|
303 |
-
why_not_fast_path = (
|
304 |
-
"key_padding_mask is not supported with NestedTensor input"
|
305 |
-
)
|
306 |
-
elif self.num_heads % 2 == 1:
|
307 |
-
why_not_fast_path = "num_heads is odd"
|
308 |
-
elif torch.is_autocast_enabled():
|
309 |
-
why_not_fast_path = "autocast is enabled"
|
310 |
-
|
311 |
-
if not why_not_fast_path:
|
312 |
-
tensor_args = (
|
313 |
-
query,
|
314 |
-
key,
|
315 |
-
value,
|
316 |
-
self.in_proj_weight,
|
317 |
-
self.in_proj_bias,
|
318 |
-
self.out_proj.weight,
|
319 |
-
self.out_proj.bias,
|
320 |
-
)
|
321 |
-
# We have to use list comprehensions below because TorchScript does not support
|
322 |
-
# generator expressions.
|
323 |
-
if torch.overrides.has_torch_function(tensor_args):
|
324 |
-
why_not_fast_path = "some Tensor argument has_torch_function"
|
325 |
-
elif not all(
|
326 |
-
[
|
327 |
-
(x is None or x.is_cuda or "cpu" in str(x.device))
|
328 |
-
for x in tensor_args
|
329 |
-
]
|
330 |
-
):
|
331 |
-
why_not_fast_path = "some Tensor argument is neither CUDA nor CPU"
|
332 |
-
elif torch.is_grad_enabled() and any(
|
333 |
-
[x is not None and x.requires_grad for x in tensor_args]
|
334 |
-
):
|
335 |
-
why_not_fast_path = (
|
336 |
-
"grad is enabled and at least one of query or the "
|
337 |
-
"input/output projection weights or biases requires_grad"
|
338 |
-
)
|
339 |
-
if not why_not_fast_path:
|
340 |
-
return torch._native_multi_head_attention(
|
341 |
-
query,
|
342 |
-
key,
|
343 |
-
value,
|
344 |
-
self.embed_dim,
|
345 |
-
self.num_heads,
|
346 |
-
self.in_proj_weight,
|
347 |
-
self.in_proj_bias,
|
348 |
-
self.out_proj.weight,
|
349 |
-
self.out_proj.bias,
|
350 |
-
key_padding_mask if key_padding_mask is not None else attn_mask,
|
351 |
-
need_weights,
|
352 |
-
average_attn_weights,
|
353 |
-
1
|
354 |
-
if key_padding_mask is not None
|
355 |
-
else 0
|
356 |
-
if attn_mask is not None
|
357 |
-
else None,
|
358 |
-
)
|
359 |
-
|
360 |
-
any_nested = query.is_nested or key.is_nested or value.is_nested
|
361 |
-
assert not any_nested, (
|
362 |
-
"MultiheadAttention does not support NestedTensor outside of its fast path. "
|
363 |
-
+ f"The fast path was not hit because {why_not_fast_path}"
|
364 |
-
)
|
365 |
-
|
366 |
-
if self.batch_first and is_batched:
|
367 |
-
# make sure that the transpose op does not affect the "is" property
|
368 |
-
if key is value:
|
369 |
-
if query is key:
|
370 |
-
query = key = value = query.transpose(1, 0)
|
371 |
-
else:
|
372 |
-
query, key = [x.transpose(1, 0) for x in (query, key)]
|
373 |
-
value = key
|
374 |
-
else:
|
375 |
-
query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
|
376 |
-
|
377 |
-
if not self._qkv_same_embed_dim:
|
378 |
-
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
379 |
-
query,
|
380 |
-
key,
|
381 |
-
value,
|
382 |
-
self.embed_dim,
|
383 |
-
self.num_heads,
|
384 |
-
self.in_proj_weight,
|
385 |
-
self.in_proj_bias,
|
386 |
-
self.bias_k,
|
387 |
-
self.bias_v,
|
388 |
-
self.add_zero_attn,
|
389 |
-
self.dropout,
|
390 |
-
self.out_proj.weight,
|
391 |
-
self.out_proj.bias,
|
392 |
-
training=self.training,
|
393 |
-
key_padding_mask=key_padding_mask,
|
394 |
-
need_weights=need_weights,
|
395 |
-
attn_mask=attn_mask,
|
396 |
-
use_separate_proj_weight=True,
|
397 |
-
q_proj_weight=self.q_proj_weight,
|
398 |
-
k_proj_weight=self.k_proj_weight,
|
399 |
-
v_proj_weight=self.v_proj_weight,
|
400 |
-
average_attn_weights=average_attn_weights,
|
401 |
-
cache=cache,
|
402 |
-
)
|
403 |
-
else:
|
404 |
-
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
405 |
-
query,
|
406 |
-
key,
|
407 |
-
value,
|
408 |
-
self.embed_dim,
|
409 |
-
self.num_heads,
|
410 |
-
self.in_proj_weight,
|
411 |
-
self.in_proj_bias,
|
412 |
-
self.bias_k,
|
413 |
-
self.bias_v,
|
414 |
-
self.add_zero_attn,
|
415 |
-
self.dropout,
|
416 |
-
self.out_proj.weight,
|
417 |
-
self.out_proj.bias,
|
418 |
-
training=self.training,
|
419 |
-
key_padding_mask=key_padding_mask,
|
420 |
-
need_weights=need_weights,
|
421 |
-
attn_mask=attn_mask,
|
422 |
-
average_attn_weights=average_attn_weights,
|
423 |
-
cache=cache,
|
424 |
-
)
|
425 |
-
if self.batch_first and is_batched:
|
426 |
-
return attn_output.transpose(1, 0), attn_output_weights
|
427 |
-
else:
|
428 |
-
return attn_output, attn_output_weights
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/activation_onnx.py
DELETED
@@ -1,178 +0,0 @@
|
|
1 |
-
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
|
2 |
-
from typing import Optional
|
3 |
-
from typing import Tuple
|
4 |
-
import torch
|
5 |
-
from torch import Tensor
|
6 |
-
from torch.nn import Linear
|
7 |
-
from torch.nn import Module
|
8 |
-
from torch.nn.init import constant_
|
9 |
-
from torch.nn.init import xavier_normal_
|
10 |
-
from torch.nn.init import xavier_uniform_
|
11 |
-
from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
|
12 |
-
from torch.nn.parameter import Parameter
|
13 |
-
|
14 |
-
from torch.nn import functional as F
|
15 |
-
from AR.modules.patched_mha_with_cache_onnx import multi_head_attention_forward_patched
|
16 |
-
|
17 |
-
|
18 |
-
class MultiheadAttention(Module):
|
19 |
-
__constants__ = ["batch_first"]
|
20 |
-
bias_k: Optional[torch.Tensor]
|
21 |
-
bias_v: Optional[torch.Tensor]
|
22 |
-
|
23 |
-
def __init__(
|
24 |
-
self,
|
25 |
-
embed_dim,
|
26 |
-
num_heads,
|
27 |
-
dropout=0.0,
|
28 |
-
bias=True,
|
29 |
-
add_bias_kv=False,
|
30 |
-
add_zero_attn=False,
|
31 |
-
kdim=None,
|
32 |
-
vdim=None,
|
33 |
-
batch_first=False,
|
34 |
-
linear1_cls=Linear,
|
35 |
-
linear2_cls=Linear,
|
36 |
-
device=None,
|
37 |
-
dtype=None,
|
38 |
-
) -> None:
|
39 |
-
factory_kwargs = {"device": device, "dtype": dtype}
|
40 |
-
super(MultiheadAttention, self).__init__()
|
41 |
-
self.embed_dim = embed_dim
|
42 |
-
self.kdim = kdim if kdim is not None else embed_dim
|
43 |
-
self.vdim = vdim if vdim is not None else embed_dim
|
44 |
-
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
45 |
-
|
46 |
-
self.num_heads = num_heads
|
47 |
-
self.dropout = dropout
|
48 |
-
self.batch_first = batch_first
|
49 |
-
self.head_dim = embed_dim // num_heads
|
50 |
-
assert (
|
51 |
-
self.head_dim * num_heads == self.embed_dim
|
52 |
-
), "embed_dim must be divisible by num_heads"
|
53 |
-
|
54 |
-
if add_bias_kv:
|
55 |
-
self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
56 |
-
self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
57 |
-
else:
|
58 |
-
self.bias_k = self.bias_v = None
|
59 |
-
|
60 |
-
if linear1_cls == Linear:
|
61 |
-
if not self._qkv_same_embed_dim:
|
62 |
-
self.q_proj_weight = Parameter(
|
63 |
-
torch.empty((embed_dim, embed_dim), **factory_kwargs)
|
64 |
-
)
|
65 |
-
self.k_proj_weight = Parameter(
|
66 |
-
torch.empty((embed_dim, self.kdim), **factory_kwargs)
|
67 |
-
)
|
68 |
-
self.v_proj_weight = Parameter(
|
69 |
-
torch.empty((embed_dim, self.vdim), **factory_kwargs)
|
70 |
-
)
|
71 |
-
self.register_parameter("in_proj_weight", None)
|
72 |
-
else:
|
73 |
-
self.in_proj_weight = Parameter(
|
74 |
-
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
|
75 |
-
)
|
76 |
-
self.register_parameter("q_proj_weight", None)
|
77 |
-
self.register_parameter("k_proj_weight", None)
|
78 |
-
self.register_parameter("v_proj_weight", None)
|
79 |
-
|
80 |
-
if bias:
|
81 |
-
self.in_proj_bias = Parameter(
|
82 |
-
torch.empty(3 * embed_dim, **factory_kwargs)
|
83 |
-
)
|
84 |
-
else:
|
85 |
-
self.register_parameter("in_proj_bias", None)
|
86 |
-
self.out_proj = NonDynamicallyQuantizableLinear(
|
87 |
-
embed_dim, embed_dim, bias=bias, **factory_kwargs
|
88 |
-
)
|
89 |
-
|
90 |
-
self._reset_parameters()
|
91 |
-
else:
|
92 |
-
if not self._qkv_same_embed_dim:
|
93 |
-
raise NotImplementedError
|
94 |
-
else:
|
95 |
-
self.in_proj_linear = linear1_cls(
|
96 |
-
embed_dim, 3 * embed_dim, bias=bias, **factory_kwargs
|
97 |
-
)
|
98 |
-
self.in_proj_weight = self.in_proj_linear.weight
|
99 |
-
|
100 |
-
self.register_parameter("q_proj_weight", None)
|
101 |
-
self.register_parameter("k_proj_weight", None)
|
102 |
-
self.register_parameter("v_proj_weight", None)
|
103 |
-
|
104 |
-
if bias:
|
105 |
-
self.in_proj_bias = self.in_proj_linear.bias
|
106 |
-
else:
|
107 |
-
self.register_parameter("in_proj_bias", None)
|
108 |
-
|
109 |
-
self.out_proj = linear2_cls(
|
110 |
-
embed_dim, embed_dim, bias=bias, **factory_kwargs
|
111 |
-
)
|
112 |
-
|
113 |
-
if self.bias_k is not None:
|
114 |
-
xavier_normal_(self.bias_k)
|
115 |
-
if self.bias_v is not None:
|
116 |
-
xavier_normal_(self.bias_v)
|
117 |
-
|
118 |
-
self.add_zero_attn = add_zero_attn
|
119 |
-
|
120 |
-
def _reset_parameters(self):
|
121 |
-
if self._qkv_same_embed_dim:
|
122 |
-
xavier_uniform_(self.in_proj_weight)
|
123 |
-
else:
|
124 |
-
xavier_uniform_(self.q_proj_weight)
|
125 |
-
xavier_uniform_(self.k_proj_weight)
|
126 |
-
xavier_uniform_(self.v_proj_weight)
|
127 |
-
|
128 |
-
if self.in_proj_bias is not None:
|
129 |
-
constant_(self.in_proj_bias, 0.0)
|
130 |
-
constant_(self.out_proj.bias, 0.0)
|
131 |
-
|
132 |
-
if self.bias_k is not None:
|
133 |
-
xavier_normal_(self.bias_k)
|
134 |
-
if self.bias_v is not None:
|
135 |
-
xavier_normal_(self.bias_v)
|
136 |
-
|
137 |
-
def __setstate__(self, state):
|
138 |
-
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
|
139 |
-
if "_qkv_same_embed_dim" not in state:
|
140 |
-
state["_qkv_same_embed_dim"] = True
|
141 |
-
|
142 |
-
super(MultiheadAttention, self).__setstate__(state)
|
143 |
-
|
144 |
-
def forward(
|
145 |
-
self,
|
146 |
-
query: Tensor,
|
147 |
-
key: Tensor,
|
148 |
-
value: Tensor,
|
149 |
-
key_padding_mask: Optional[Tensor] = None,
|
150 |
-
need_weights: bool = True,
|
151 |
-
attn_mask: Optional[Tensor] = None,
|
152 |
-
average_attn_weights: bool = True,
|
153 |
-
cache=None,
|
154 |
-
) -> Tuple[Tensor, Optional[Tensor]]:
|
155 |
-
any_nested = query.is_nested or key.is_nested or value.is_nested
|
156 |
-
query = key = value = query.transpose(1, 0)
|
157 |
-
attn_output = multi_head_attention_forward_patched(
|
158 |
-
query,
|
159 |
-
key,
|
160 |
-
value,
|
161 |
-
self.embed_dim,
|
162 |
-
self.num_heads,
|
163 |
-
self.in_proj_weight,
|
164 |
-
self.in_proj_bias,
|
165 |
-
self.bias_k,
|
166 |
-
self.bias_v,
|
167 |
-
self.add_zero_attn,
|
168 |
-
self.dropout,
|
169 |
-
self.out_proj.weight,
|
170 |
-
self.out_proj.bias,
|
171 |
-
training=self.training,
|
172 |
-
key_padding_mask=key_padding_mask,
|
173 |
-
need_weights=need_weights,
|
174 |
-
attn_mask=attn_mask,
|
175 |
-
average_attn_weights=average_attn_weights,
|
176 |
-
cache=cache,
|
177 |
-
)
|
178 |
-
return attn_output.transpose(1, 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/embedding_onnx.py
DELETED
@@ -1,63 +0,0 @@
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/lr_schedulers.py
DELETED
@@ -1,83 +0,0 @@
|
|
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) / (
|
53 |
-
self.total_steps - self.warmup_steps
|
54 |
-
)
|
55 |
-
if decay_ratio < 0.0 or decay_ratio > 1.0:
|
56 |
-
raise RuntimeError(
|
57 |
-
"Decay ratio must be in [0.0, 1.0]. Fix LR scheduler settings."
|
58 |
-
)
|
59 |
-
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
|
60 |
-
lr = self.end_lr + coeff * (self.peak_lr - self.end_lr)
|
61 |
-
|
62 |
-
self.lr = lr = self.end_lr = 0.002 ###锁定用线性###不听话,直接锁定!
|
63 |
-
self.set_lr(lr)
|
64 |
-
self.lr = lr
|
65 |
-
self._current_step += 1
|
66 |
-
return self.lr
|
67 |
-
|
68 |
-
|
69 |
-
if __name__ == "__main__":
|
70 |
-
m = nn.Linear(10, 10)
|
71 |
-
opt = Adam(m.parameters(), lr=1e-4)
|
72 |
-
s = WarmupCosineLRSchedule(
|
73 |
-
opt, 1e-6, 2e-4, 1e-6, warmup_steps=2000, total_steps=20000, current_step=0
|
74 |
-
)
|
75 |
-
lrs = []
|
76 |
-
for i in range(25000):
|
77 |
-
s.step()
|
78 |
-
lrs.append(s.lr)
|
79 |
-
print(s.lr)
|
80 |
-
|
81 |
-
plt.plot(lrs)
|
82 |
-
plt.plot(range(0, 25000), lrs)
|
83 |
-
plt.show()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/optim.py
DELETED
@@ -1,622 +0,0 @@
|
|
1 |
-
# Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
|
2 |
-
#
|
3 |
-
# See ../LICENSE for clarification regarding multiple authors
|
4 |
-
#
|
5 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
-
# you may not use this file except in compliance with the License.
|
7 |
-
# You may obtain a copy of the License at
|
8 |
-
#
|
9 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
-
#
|
11 |
-
# Unless required by applicable law or agreed to in writing, software
|
12 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
-
# See the License for the specific language governing permissions and
|
15 |
-
# limitations under the License.
|
16 |
-
import contextlib
|
17 |
-
import logging
|
18 |
-
from collections import defaultdict
|
19 |
-
from typing import List
|
20 |
-
from typing import Tuple
|
21 |
-
|
22 |
-
import torch
|
23 |
-
from torch import Tensor
|
24 |
-
from torch.optim import Optimizer
|
25 |
-
|
26 |
-
|
27 |
-
class BatchedOptimizer(Optimizer):
|
28 |
-
"""
|
29 |
-
This class adds to class Optimizer the capability to optimize parameters in batches:
|
30 |
-
it will stack the parameters and their grads for you so the optimizer can work
|
31 |
-
on tensors with an extra leading dimension. This is intended for speed with GPUs,
|
32 |
-
as it reduces the number of kernels launched in the optimizer.
|
33 |
-
|
34 |
-
Args:
|
35 |
-
params:
|
36 |
-
"""
|
37 |
-
|
38 |
-
def __init__(self, params, defaults):
|
39 |
-
super(BatchedOptimizer, self).__init__(params, defaults)
|
40 |
-
|
41 |
-
@contextlib.contextmanager
|
42 |
-
def batched_params(self, param_group, group_params_names):
|
43 |
-
"""
|
44 |
-
This function returns (technically, yields) a list of
|
45 |
-
of tuples (p, state), where
|
46 |
-
p is a `fake` parameter that is stacked (over axis 0) from real parameters
|
47 |
-
that share the same shape, and its gradient is also stacked;
|
48 |
-
`state` is the state corresponding to this batch of parameters
|
49 |
-
(it will be physically located in the "state" for one of the real
|
50 |
-
parameters, the last one that has any particular shape and dtype).
|
51 |
-
|
52 |
-
This function is decorated as a context manager so that it can
|
53 |
-
write parameters back to their "real" locations.
|
54 |
-
|
55 |
-
The idea is, instead of doing:
|
56 |
-
<code>
|
57 |
-
for p in group["params"]:
|
58 |
-
state = self.state[p]
|
59 |
-
...
|
60 |
-
</code>
|
61 |
-
you can do:
|
62 |
-
<code>
|
63 |
-
with self.batched_params(group["params"]) as batches:
|
64 |
-
for p, state, p_names in batches:
|
65 |
-
...
|
66 |
-
</code>
|
67 |
-
|
68 |
-
Args:
|
69 |
-
group: a parameter group, which is a list of parameters; should be
|
70 |
-
one of self.param_groups.
|
71 |
-
group_params_names: name for each parameter in group,
|
72 |
-
which is List[str].
|
73 |
-
"""
|
74 |
-
batches = defaultdict(
|
75 |
-
list
|
76 |
-
) # `batches` maps from tuple (dtype_as_str,*shape) to list of nn.Parameter
|
77 |
-
batches_names = defaultdict(
|
78 |
-
list
|
79 |
-
) # `batches` maps from tuple (dtype_as_str,*shape) to list of str
|
80 |
-
|
81 |
-
assert len(param_group) == len(group_params_names)
|
82 |
-
for p, named_p in zip(param_group, group_params_names):
|
83 |
-
key = (str(p.dtype), *p.shape)
|
84 |
-
batches[key].append(p)
|
85 |
-
batches_names[key].append(named_p)
|
86 |
-
|
87 |
-
batches_names_keys = list(batches_names.keys())
|
88 |
-
sorted_idx = sorted(
|
89 |
-
range(len(batches_names)), key=lambda i: batches_names_keys[i])
|
90 |
-
batches_names = [
|
91 |
-
batches_names[batches_names_keys[idx]] for idx in sorted_idx
|
92 |
-
]
|
93 |
-
batches = [batches[batches_names_keys[idx]] for idx in sorted_idx]
|
94 |
-
|
95 |
-
stacked_params_dict = dict()
|
96 |
-
|
97 |
-
# turn batches into a list, in deterministic order.
|
98 |
-
# tuples will contain tuples of (stacked_param, state, stacked_params_names),
|
99 |
-
# one for each batch in `batches`.
|
100 |
-
tuples = []
|
101 |
-
|
102 |
-
for batch, batch_names in zip(batches, batches_names):
|
103 |
-
p = batch[0]
|
104 |
-
# we arbitrarily store the state in the
|
105 |
-
# state corresponding to the 1st parameter in the
|
106 |
-
# group. class Optimizer will take care of saving/loading state.
|
107 |
-
state = self.state[p]
|
108 |
-
p_stacked = torch.stack(batch)
|
109 |
-
grad = torch.stack([
|
110 |
-
torch.zeros_like(p) if p.grad is None else p.grad for p in batch
|
111 |
-
])
|
112 |
-
p_stacked.grad = grad
|
113 |
-
stacked_params_dict[key] = p_stacked
|
114 |
-
tuples.append((p_stacked, state, batch_names))
|
115 |
-
|
116 |
-
yield tuples # <-- calling code will do the actual optimization here!
|
117 |
-
|
118 |
-
for ((stacked_params, _state, _names), batch) in zip(tuples, batches):
|
119 |
-
for i, p in enumerate(batch): # batch is list of Parameter
|
120 |
-
p.copy_(stacked_params[i])
|
121 |
-
|
122 |
-
|
123 |
-
class ScaledAdam(BatchedOptimizer):
|
124 |
-
"""
|
125 |
-
Implements 'Scaled Adam', a variant of Adam where we scale each parameter's update
|
126 |
-
proportional to the norm of that parameter; and also learn the scale of the parameter,
|
127 |
-
in log space, subject to upper and lower limits (as if we had factored each parameter as
|
128 |
-
param = underlying_param * log_scale.exp())
|
129 |
-
|
130 |
-
|
131 |
-
Args:
|
132 |
-
params: The parameters or param_groups to optimize (like other Optimizer subclasses)
|
133 |
-
lr: The learning rate. We will typically use a learning rate schedule that starts
|
134 |
-
at 0.03 and decreases over time, i.e. much higher than other common
|
135 |
-
optimizers.
|
136 |
-
clipping_scale: (e.g. 2.0)
|
137 |
-
A scale for gradient-clipping: if specified, the normalized gradients
|
138 |
-
over the whole model will be clipped to have 2-norm equal to
|
139 |
-
`clipping_scale` times the median 2-norm over the most recent period
|
140 |
-
of `clipping_update_period` minibatches. By "normalized gradients",
|
141 |
-
we mean after multiplying by the rms parameter value for this tensor
|
142 |
-
[for non-scalars]; this is appropriate because our update is scaled
|
143 |
-
by this quantity.
|
144 |
-
betas: beta1,beta2 are momentum constants for regular momentum, and moving sum-sq grad.
|
145 |
-
Must satisfy 0 < beta <= beta2 < 1.
|
146 |
-
scalar_lr_scale: A scaling factor on the learning rate, that we use to update the
|
147 |
-
scale of each parameter tensor and scalar parameters of the mode..
|
148 |
-
If each parameter were decomposed
|
149 |
-
as p * p_scale.exp(), where (p**2).mean().sqrt() == 1.0, scalar_lr_scale
|
150 |
-
would be a the scaling factor on the learning rate of p_scale.
|
151 |
-
eps: A general-purpose epsilon to prevent division by zero
|
152 |
-
param_min_rms: Minimum root-mean-square value of parameter tensor, for purposes of
|
153 |
-
learning the scale on the parameters (we'll constrain the rms of each non-scalar
|
154 |
-
parameter tensor to be >= this value)
|
155 |
-
param_max_rms: Maximum root-mean-square value of parameter tensor, for purposes of
|
156 |
-
learning the scale on the parameters (we'll constrain the rms of each non-scalar
|
157 |
-
parameter tensor to be <= this value)
|
158 |
-
scalar_max: Maximum absolute value for scalar parameters (applicable if your
|
159 |
-
model has any parameters with numel() == 1).
|
160 |
-
size_update_period: The periodicity, in steps, with which we update the size (scale)
|
161 |
-
of the parameter tensor. This is provided to save a little time
|
162 |
-
in the update.
|
163 |
-
clipping_update_period: if clipping_scale is specified, this is the period
|
164 |
-
"""
|
165 |
-
|
166 |
-
def __init__(
|
167 |
-
self,
|
168 |
-
params,
|
169 |
-
lr=3e-02,
|
170 |
-
clipping_scale=None,
|
171 |
-
betas=(0.9, 0.98),
|
172 |
-
scalar_lr_scale=0.1,
|
173 |
-
eps=1.0e-08,
|
174 |
-
param_min_rms=1.0e-05,
|
175 |
-
param_max_rms=3.0,
|
176 |
-
scalar_max=10.0,
|
177 |
-
size_update_period=4,
|
178 |
-
clipping_update_period=100,
|
179 |
-
parameters_names=None,
|
180 |
-
show_dominant_parameters=True, ):
|
181 |
-
|
182 |
-
assert parameters_names is not None, (
|
183 |
-
"Please prepare parameters_names,"
|
184 |
-
"which is a List[List[str]]. Each List[str] is for a group"
|
185 |
-
"and each str is for a parameter")
|
186 |
-
defaults = dict(
|
187 |
-
lr=lr,
|
188 |
-
clipping_scale=clipping_scale,
|
189 |
-
betas=betas,
|
190 |
-
scalar_lr_scale=scalar_lr_scale,
|
191 |
-
eps=eps,
|
192 |
-
param_min_rms=param_min_rms,
|
193 |
-
param_max_rms=param_max_rms,
|
194 |
-
scalar_max=scalar_max,
|
195 |
-
size_update_period=size_update_period,
|
196 |
-
clipping_update_period=clipping_update_period, )
|
197 |
-
|
198 |
-
super(ScaledAdam, self).__init__(params, defaults)
|
199 |
-
assert len(self.param_groups) == len(parameters_names)
|
200 |
-
self.parameters_names = parameters_names
|
201 |
-
self.show_dominant_parameters = show_dominant_parameters
|
202 |
-
|
203 |
-
def __setstate__(self, state):
|
204 |
-
super(ScaledAdam, self).__setstate__(state)
|
205 |
-
|
206 |
-
@torch.no_grad()
|
207 |
-
def step(self, closure=None):
|
208 |
-
"""Performs a single optimization step.
|
209 |
-
|
210 |
-
Arguments:
|
211 |
-
closure (callable, optional): A closure that reevaluates the model
|
212 |
-
and returns the loss.
|
213 |
-
"""
|
214 |
-
loss = None
|
215 |
-
if closure is not None:
|
216 |
-
with torch.enable_grad():
|
217 |
-
loss = closure()
|
218 |
-
|
219 |
-
batch = True
|
220 |
-
|
221 |
-
for group, group_params_names in zip(self.param_groups,
|
222 |
-
self.parameters_names):
|
223 |
-
|
224 |
-
with self.batched_params(group["params"],
|
225 |
-
group_params_names) as batches:
|
226 |
-
|
227 |
-
# batches is list of pairs (stacked_param, state). stacked_param is like
|
228 |
-
# a regular parameter, and will have a .grad, but the 1st dim corresponds to
|
229 |
-
# a stacking dim, it is not a real dim.
|
230 |
-
|
231 |
-
if (len(batches[0][1]) ==
|
232 |
-
0): # if len(first state) == 0: not yet initialized
|
233 |
-
clipping_scale = 1
|
234 |
-
else:
|
235 |
-
clipping_scale = self._get_clipping_scale(group, batches)
|
236 |
-
|
237 |
-
for p, state, _ in batches:
|
238 |
-
# Perform optimization step.
|
239 |
-
# grad is not going to be None, we handled that when creating the batches.
|
240 |
-
grad = p.grad
|
241 |
-
if grad.is_sparse:
|
242 |
-
raise RuntimeError(
|
243 |
-
"ScaledAdam optimizer does not support sparse gradients"
|
244 |
-
)
|
245 |
-
# State initialization
|
246 |
-
if len(state) == 0:
|
247 |
-
self._init_state(group, p, state)
|
248 |
-
|
249 |
-
self._step_one_batch(group, p, state, clipping_scale)
|
250 |
-
|
251 |
-
return loss
|
252 |
-
|
253 |
-
def _init_state(self, group: dict, p: Tensor, state: dict):
|
254 |
-
"""
|
255 |
-
Initializes state dict for parameter 'p'. Assumes that dim 0 of tensor p
|
256 |
-
is actually the batch dimension, corresponding to batched-together
|
257 |
-
parameters of a given shape.
|
258 |
-
|
259 |
-
|
260 |
-
Args:
|
261 |
-
group: Dict to look up configuration values.
|
262 |
-
p: The parameter that we are initializing the state for
|
263 |
-
state: Dict from string to whatever state we are initializing
|
264 |
-
"""
|
265 |
-
size_update_period = group["size_update_period"]
|
266 |
-
|
267 |
-
state["step"] = 0
|
268 |
-
|
269 |
-
kwargs = {"device": p.device, "dtype": p.dtype}
|
270 |
-
|
271 |
-
# 'delta' implements conventional momentum. There are
|
272 |
-
# several different kinds of update going on, so rather than
|
273 |
-
# compute "exp_avg" like in Adam, we store and decay a
|
274 |
-
# parameter-change "delta", which combines all forms of
|
275 |
-
# update. this is equivalent to how it's done in Adam,
|
276 |
-
# except for the first few steps.
|
277 |
-
state["delta"] = torch.zeros_like(
|
278 |
-
p, memory_format=torch.preserve_format)
|
279 |
-
|
280 |
-
batch_size = p.shape[0]
|
281 |
-
numel = p.numel() // batch_size
|
282 |
-
numel = p.numel()
|
283 |
-
|
284 |
-
if numel > 1:
|
285 |
-
# "param_rms" just periodically records the scalar root-mean-square value of
|
286 |
-
# the parameter tensor.
|
287 |
-
# it has a shape like (batch_size, 1, 1, 1, 1)
|
288 |
-
param_rms = (
|
289 |
-
(p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt())
|
290 |
-
state["param_rms"] = param_rms
|
291 |
-
|
292 |
-
state["scale_exp_avg_sq"] = torch.zeros_like(param_rms)
|
293 |
-
state["scale_grads"] = torch.zeros(size_update_period,
|
294 |
-
*param_rms.shape, **kwargs)
|
295 |
-
|
296 |
-
# exp_avg_sq is the weighted sum of scaled gradients. as in Adam.
|
297 |
-
state["exp_avg_sq"] = torch.zeros_like(
|
298 |
-
p, memory_format=torch.preserve_format)
|
299 |
-
|
300 |
-
def _get_clipping_scale(self,
|
301 |
-
group: dict,
|
302 |
-
tuples: List[Tuple[Tensor, dict, List[str]]]
|
303 |
-
) -> float:
|
304 |
-
"""
|
305 |
-
Returns a scalar factor <= 1.0 that dictates gradient clipping, i.e. we will scale the gradients
|
306 |
-
by this amount before applying the rest of the update.
|
307 |
-
|
308 |
-
Args:
|
309 |
-
group: the parameter group, an item in self.param_groups
|
310 |
-
tuples: a list of tuples of (param, state, param_names)
|
311 |
-
where param is a batched set of parameters,
|
312 |
-
with a .grad (1st dim is batch dim)
|
313 |
-
and state is the state-dict where optimization parameters are kept.
|
314 |
-
param_names is a List[str] while each str is name for a parameter
|
315 |
-
in batched set of parameters "param".
|
316 |
-
"""
|
317 |
-
assert len(tuples) >= 1
|
318 |
-
clipping_scale = group["clipping_scale"]
|
319 |
-
(first_p, first_state, _) = tuples[0]
|
320 |
-
step = first_state["step"]
|
321 |
-
if clipping_scale is None or step == 0:
|
322 |
-
# no clipping. return early on step == 0 because the other
|
323 |
-
# parameters' state won't have been initialized yet.
|
324 |
-
return 1.0
|
325 |
-
clipping_update_period = group["clipping_update_period"]
|
326 |
-
|
327 |
-
tot_sumsq = torch.tensor(0.0, device=first_p.device)
|
328 |
-
for (p, state, param_names) in tuples:
|
329 |
-
grad = p.grad
|
330 |
-
if grad.is_sparse:
|
331 |
-
raise RuntimeError(
|
332 |
-
"ScaledAdam optimizer does not support sparse gradients")
|
333 |
-
if p.numel() == p.shape[0]: # a batch of scalars
|
334 |
-
tot_sumsq += (grad**2).sum() # sum() to change shape [1] to []
|
335 |
-
else:
|
336 |
-
tot_sumsq += ((grad * state["param_rms"])**2).sum()
|
337 |
-
|
338 |
-
tot_norm = tot_sumsq.sqrt()
|
339 |
-
if "model_norms" not in first_state:
|
340 |
-
first_state["model_norms"] = torch.zeros(
|
341 |
-
clipping_update_period, device=p.device)
|
342 |
-
first_state["model_norms"][step % clipping_update_period] = tot_norm
|
343 |
-
|
344 |
-
if step % clipping_update_period == 0:
|
345 |
-
# Print some stats.
|
346 |
-
# We don't reach here if step == 0 because we would have returned
|
347 |
-
# above.
|
348 |
-
sorted_norms = first_state["model_norms"].sort()[0].to("cpu")
|
349 |
-
quartiles = []
|
350 |
-
for n in range(0, 5):
|
351 |
-
index = min(
|
352 |
-
clipping_update_period - 1,
|
353 |
-
(clipping_update_period // 4) * n, )
|
354 |
-
quartiles.append(sorted_norms[index].item())
|
355 |
-
|
356 |
-
median = quartiles[2]
|
357 |
-
threshold = clipping_scale * median
|
358 |
-
first_state["model_norm_threshold"] = threshold
|
359 |
-
percent_clipped = (first_state["num_clipped"] * 100.0 /
|
360 |
-
clipping_update_period
|
361 |
-
if "num_clipped" in first_state else 0.0)
|
362 |
-
first_state["num_clipped"] = 0
|
363 |
-
quartiles = " ".join(["%.3e" % x for x in quartiles])
|
364 |
-
logging.info(
|
365 |
-
f"Clipping_scale={clipping_scale}, grad-norm quartiles {quartiles}, "
|
366 |
-
f"threshold={threshold:.3e}, percent-clipped={percent_clipped:.1f}"
|
367 |
-
)
|
368 |
-
|
369 |
-
if step < clipping_update_period:
|
370 |
-
return 1.0 # We have not yet estimated a norm to clip to.
|
371 |
-
else:
|
372 |
-
try:
|
373 |
-
model_norm_threshold = first_state["model_norm_threshold"]
|
374 |
-
except KeyError:
|
375 |
-
logging.info(
|
376 |
-
"Warning: model_norm_threshold not in state: possibly "
|
377 |
-
"you changed config when restarting, adding clipping_scale option?"
|
378 |
-
)
|
379 |
-
return 1.0
|
380 |
-
ans = min(1.0, (model_norm_threshold / (tot_norm + 1.0e-20)).item())
|
381 |
-
if ans < 1.0:
|
382 |
-
first_state["num_clipped"] += 1
|
383 |
-
if ans < 0.1:
|
384 |
-
logging.warn(
|
385 |
-
f"Scaling gradients by {ans}, model_norm_threshold={model_norm_threshold}"
|
386 |
-
)
|
387 |
-
if self.show_dominant_parameters:
|
388 |
-
assert p.shape[0] == len(param_names)
|
389 |
-
self._show_gradient_dominating_parameter(tuples, tot_sumsq)
|
390 |
-
return ans
|
391 |
-
|
392 |
-
def _show_gradient_dominating_parameter(
|
393 |
-
self, tuples: List[Tuple[Tensor, dict, List[str]]],
|
394 |
-
tot_sumsq: Tensor):
|
395 |
-
"""
|
396 |
-
Show information of parameter wihch dominanting tot_sumsq.
|
397 |
-
|
398 |
-
Args:
|
399 |
-
tuples: a list of tuples of (param, state, param_names)
|
400 |
-
where param is a batched set of parameters,
|
401 |
-
with a .grad (1st dim is batch dim)
|
402 |
-
and state is the state-dict where optimization parameters are kept.
|
403 |
-
param_names is a List[str] while each str is name for a parameter
|
404 |
-
in batched set of parameters "param".
|
405 |
-
tot_sumsq: sumsq of all parameters. Though it's could be calculated
|
406 |
-
from tuples, we still pass it to save some time.
|
407 |
-
"""
|
408 |
-
all_sumsq_orig = {}
|
409 |
-
for (p, state, batch_param_names) in tuples:
|
410 |
-
# p is a stacked batch parameters.
|
411 |
-
batch_grad = p.grad
|
412 |
-
if p.numel() == p.shape[0]: # a batch of scalars
|
413 |
-
batch_sumsq_orig = batch_grad**2
|
414 |
-
# Dummpy values used by following `zip` statement.
|
415 |
-
batch_rms_orig = torch.ones(p.shape[0])
|
416 |
-
else:
|
417 |
-
batch_rms_orig = state["param_rms"]
|
418 |
-
batch_sumsq_orig = ((batch_grad * batch_rms_orig)**2).sum(
|
419 |
-
dim=list(range(1, batch_grad.ndim)))
|
420 |
-
|
421 |
-
for name, sumsq_orig, rms, grad in zip(batch_param_names,
|
422 |
-
batch_sumsq_orig,
|
423 |
-
batch_rms_orig, batch_grad):
|
424 |
-
|
425 |
-
proportion_orig = sumsq_orig / tot_sumsq
|
426 |
-
all_sumsq_orig[name] = (proportion_orig, sumsq_orig, rms, grad)
|
427 |
-
|
428 |
-
assert torch.isclose(
|
429 |
-
sum([value[0] for value in all_sumsq_orig.values()]).cpu(),
|
430 |
-
torch.tensor(1.0), )
|
431 |
-
sorted_by_proportion = {
|
432 |
-
k: v
|
433 |
-
for k, v in sorted(
|
434 |
-
all_sumsq_orig.items(),
|
435 |
-
key=lambda item: item[1][0],
|
436 |
-
reverse=True, )
|
437 |
-
}
|
438 |
-
dominant_param_name = next(iter(sorted_by_proportion))
|
439 |
-
(dominant_proportion, dominant_sumsq, dominant_rms,
|
440 |
-
dominant_grad, ) = sorted_by_proportion[dominant_param_name]
|
441 |
-
logging.info(f"Parameter Dominanting tot_sumsq {dominant_param_name}"
|
442 |
-
f" with proportion {dominant_proportion:.2f},"
|
443 |
-
f" where dominant_sumsq=(grad_sumsq*orig_rms_sq)"
|
444 |
-
f"={dominant_sumsq:.3e},"
|
445 |
-
f" grad_sumsq = {(dominant_grad**2).sum():.3e},"
|
446 |
-
f" orig_rms_sq={(dominant_rms**2).item():.3e}")
|
447 |
-
|
448 |
-
def _step_one_batch(self,
|
449 |
-
group: dict,
|
450 |
-
p: Tensor,
|
451 |
-
state: dict,
|
452 |
-
clipping_scale: float):
|
453 |
-
"""
|
454 |
-
Do the step for one parameter, which is actually going to be a batch of
|
455 |
-
`real` parameters, with dim 0 as the batch dim.
|
456 |
-
Args:
|
457 |
-
group: dict to look up configuration values
|
458 |
-
p: parameter to update (actually multiple parameters stacked together
|
459 |
-
as a batch)
|
460 |
-
state: state-dict for p, to look up the optimizer state
|
461 |
-
"""
|
462 |
-
lr = group["lr"]
|
463 |
-
size_update_period = group["size_update_period"]
|
464 |
-
beta1 = group["betas"][0]
|
465 |
-
|
466 |
-
grad = p.grad
|
467 |
-
if clipping_scale != 1.0:
|
468 |
-
grad = grad * clipping_scale
|
469 |
-
step = state["step"]
|
470 |
-
delta = state["delta"]
|
471 |
-
|
472 |
-
delta.mul_(beta1)
|
473 |
-
batch_size = p.shape[0]
|
474 |
-
numel = p.numel() // batch_size
|
475 |
-
if numel > 1:
|
476 |
-
# Update the size/scale of p, and set param_rms
|
477 |
-
scale_grads = state["scale_grads"]
|
478 |
-
scale_grads[step % size_update_period] = (p * grad).sum(
|
479 |
-
dim=list(range(1, p.ndim)), keepdim=True)
|
480 |
-
if step % size_update_period == size_update_period - 1:
|
481 |
-
param_rms = state["param_rms"] # shape: (batch_size, 1, 1, ..)
|
482 |
-
param_rms.copy_((p**2)
|
483 |
-
.mean(dim=list(range(1, p.ndim)), keepdim=True)
|
484 |
-
.sqrt())
|
485 |
-
if step > 0:
|
486 |
-
# self._size_update() learns the overall scale on the
|
487 |
-
# parameter, by shrinking or expanding it.
|
488 |
-
self._size_update(group, scale_grads, p, state)
|
489 |
-
|
490 |
-
if numel == 1:
|
491 |
-
# For parameters with 1 element we just use regular Adam.
|
492 |
-
# Updates delta.
|
493 |
-
self._step_scalar(group, p, state)
|
494 |
-
else:
|
495 |
-
self._step(group, p, state)
|
496 |
-
|
497 |
-
state["step"] = step + 1
|
498 |
-
|
499 |
-
def _size_update(self,
|
500 |
-
group: dict,
|
501 |
-
scale_grads: Tensor,
|
502 |
-
p: Tensor,
|
503 |
-
state: dict) -> None:
|
504 |
-
"""
|
505 |
-
Called only where p.numel() > 1, this updates the scale of the parameter.
|
506 |
-
If we imagine: p = underlying_param * scale.exp(), and we are doing
|
507 |
-
gradient descent on underlying param and on scale, this function does the update
|
508 |
-
on `scale`.
|
509 |
-
|
510 |
-
Args:
|
511 |
-
group: dict to look up configuration values
|
512 |
-
scale_grads: a tensor of shape (size_update_period, batch_size, 1, 1,...) containing
|
513 |
-
grads w.r.t. the scales.
|
514 |
-
p: The parameter to update
|
515 |
-
state: The state-dict of p
|
516 |
-
"""
|
517 |
-
|
518 |
-
param_rms = state["param_rms"]
|
519 |
-
beta1, beta2 = group["betas"]
|
520 |
-
size_lr = group["lr"] * group["scalar_lr_scale"]
|
521 |
-
param_min_rms = group["param_min_rms"]
|
522 |
-
param_max_rms = group["param_max_rms"]
|
523 |
-
eps = group["eps"]
|
524 |
-
step = state["step"]
|
525 |
-
batch_size = p.shape[0]
|
526 |
-
|
527 |
-
size_update_period = scale_grads.shape[0]
|
528 |
-
# correct beta2 for the size update period: we will have
|
529 |
-
# faster decay at this level.
|
530 |
-
beta2_corr = beta2**size_update_period
|
531 |
-
|
532 |
-
scale_exp_avg_sq = state[
|
533 |
-
"scale_exp_avg_sq"] # shape: (batch_size, 1, 1, ..)
|
534 |
-
scale_exp_avg_sq.mul_(beta2_corr).add_(
|
535 |
-
(scale_grads**2).mean(dim=0), # mean over dim `size_update_period`
|
536 |
-
alpha=1 - beta2_corr, ) # shape is (batch_size, 1, 1, ...)
|
537 |
-
|
538 |
-
# The 1st time we reach here is when size_step == 1.
|
539 |
-
size_step = (step + 1) // size_update_period
|
540 |
-
bias_correction2 = 1 - beta2_corr**size_step
|
541 |
-
# we don't bother with bias_correction1; this will help prevent divergence
|
542 |
-
# at the start of training.
|
543 |
-
|
544 |
-
denom = scale_exp_avg_sq.sqrt() + eps
|
545 |
-
|
546 |
-
scale_step = (-size_lr * (bias_correction2**0.5) *
|
547 |
-
scale_grads.sum(dim=0) / denom)
|
548 |
-
|
549 |
-
is_too_small = param_rms < param_min_rms
|
550 |
-
is_too_large = param_rms > param_max_rms
|
551 |
-
|
552 |
-
# when the param gets too small, just don't shrink it any further.
|
553 |
-
scale_step.masked_fill_(is_too_small, 0.0)
|
554 |
-
# when it gets too large, stop it from getting any larger.
|
555 |
-
scale_step.masked_fill_(is_too_large, -size_lr * size_update_period)
|
556 |
-
delta = state["delta"]
|
557 |
-
# the factor of (1-beta1) relates to momentum.
|
558 |
-
delta.add_(p * scale_step, alpha=(1 - beta1))
|
559 |
-
|
560 |
-
def _step(self, group: dict, p: Tensor, state: dict):
|
561 |
-
"""
|
562 |
-
This function does the core update of self.step(), in the case where the members of
|
563 |
-
the batch have more than 1 element.
|
564 |
-
|
565 |
-
Args:
|
566 |
-
group: A dict which will be used to look up configuration values
|
567 |
-
p: The parameter to be updated
|
568 |
-
grad: The grad of p
|
569 |
-
state: The state-dict corresponding to parameter p
|
570 |
-
|
571 |
-
This function modifies p.
|
572 |
-
"""
|
573 |
-
grad = p.grad
|
574 |
-
lr = group["lr"]
|
575 |
-
beta1, beta2 = group["betas"]
|
576 |
-
eps = group["eps"]
|
577 |
-
param_min_rms = group["param_min_rms"]
|
578 |
-
step = state["step"]
|
579 |
-
|
580 |
-
exp_avg_sq = state["exp_avg_sq"]
|
581 |
-
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2))
|
582 |
-
|
583 |
-
this_step = state["step"] - (state["zero_step"]
|
584 |
-
if "zero_step" in state else 0)
|
585 |
-
bias_correction2 = 1 - beta2**(this_step + 1)
|
586 |
-
if bias_correction2 < 0.99:
|
587 |
-
# note: not in-place.
|
588 |
-
exp_avg_sq = exp_avg_sq * (1.0 / bias_correction2)
|
589 |
-
|
590 |
-
denom = exp_avg_sq.sqrt()
|
591 |
-
denom += eps
|
592 |
-
grad = grad / denom
|
593 |
-
|
594 |
-
alpha = -lr * (1 - beta1) * state["param_rms"].clamp(min=param_min_rms)
|
595 |
-
|
596 |
-
delta = state["delta"]
|
597 |
-
delta.add_(grad * alpha)
|
598 |
-
p.add_(delta)
|
599 |
-
|
600 |
-
def _step_scalar(self, group: dict, p: Tensor, state: dict):
|
601 |
-
"""
|
602 |
-
A simplified form of the core update for scalar tensors, where we cannot get a good
|
603 |
-
estimate of the parameter rms.
|
604 |
-
"""
|
605 |
-
beta1, beta2 = group["betas"]
|
606 |
-
scalar_max = group["scalar_max"]
|
607 |
-
eps = group["eps"]
|
608 |
-
lr = group["lr"] * group["scalar_lr_scale"]
|
609 |
-
grad = p.grad
|
610 |
-
|
611 |
-
exp_avg_sq = state["exp_avg_sq"] # shape: (batch_size,)
|
612 |
-
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
|
613 |
-
|
614 |
-
# bias_correction2 is like in Adam. Don't bother with bias_correction1;
|
615 |
-
# slower update at the start will help stability anyway.
|
616 |
-
bias_correction2 = 1 - beta2**(state["step"] + 1)
|
617 |
-
denom = (exp_avg_sq / bias_correction2).sqrt() + eps
|
618 |
-
|
619 |
-
delta = state["delta"]
|
620 |
-
delta.add_(grad / denom, alpha=-lr * (1 - beta1))
|
621 |
-
p.clamp_(min=-scalar_max, max=scalar_max)
|
622 |
-
p.add_(delta)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/patched_mha_with_cache.py
DELETED
@@ -1,465 +0,0 @@
|
|
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 |
-
from torch.nn import functional as F
|
9 |
-
import torch
|
10 |
-
# Tensor = torch.Tensor
|
11 |
-
# from typing import Callable, List, Optional, Tuple, Union
|
12 |
-
|
13 |
-
|
14 |
-
def multi_head_attention_forward_patched(
|
15 |
-
query: Tensor,
|
16 |
-
key: Tensor,
|
17 |
-
value: Tensor,
|
18 |
-
embed_dim_to_check: int,
|
19 |
-
num_heads: int,
|
20 |
-
in_proj_weight: Optional[Tensor],
|
21 |
-
in_proj_bias: Optional[Tensor],
|
22 |
-
bias_k: Optional[Tensor],
|
23 |
-
bias_v: Optional[Tensor],
|
24 |
-
add_zero_attn: bool,
|
25 |
-
dropout_p: float,
|
26 |
-
out_proj_weight: Tensor,
|
27 |
-
out_proj_bias: Optional[Tensor],
|
28 |
-
training: bool = True,
|
29 |
-
key_padding_mask: Optional[Tensor] = None,
|
30 |
-
need_weights: bool = True,
|
31 |
-
attn_mask: Optional[Tensor] = None,
|
32 |
-
use_separate_proj_weight: bool = False,
|
33 |
-
q_proj_weight: Optional[Tensor] = None,
|
34 |
-
k_proj_weight: Optional[Tensor] = None,
|
35 |
-
v_proj_weight: Optional[Tensor] = None,
|
36 |
-
static_k: Optional[Tensor] = None,
|
37 |
-
static_v: Optional[Tensor] = None,
|
38 |
-
average_attn_weights: bool = True,
|
39 |
-
is_causal: bool = False,
|
40 |
-
cache=None,
|
41 |
-
) -> Tuple[Tensor, Optional[Tensor]]:
|
42 |
-
r"""
|
43 |
-
Args:
|
44 |
-
query, key, value: map a query and a set of key-value pairs to an output.
|
45 |
-
See "Attention Is All You Need" for more details.
|
46 |
-
embed_dim_to_check: total dimension of the model.
|
47 |
-
num_heads: parallel attention heads.
|
48 |
-
in_proj_weight, in_proj_bias: input projection weight and bias.
|
49 |
-
bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
|
50 |
-
add_zero_attn: add a new batch of zeros to the key and
|
51 |
-
value sequences at dim=1.
|
52 |
-
dropout_p: probability of an element to be zeroed.
|
53 |
-
out_proj_weight, out_proj_bias: the output projection weight and bias.
|
54 |
-
training: apply dropout if is ``True``.
|
55 |
-
key_padding_mask: if provided, specified padding elements in the key will
|
56 |
-
be ignored by the attention. This is an binary mask. When the value is True,
|
57 |
-
the corresponding value on the attention layer will be filled with -inf.
|
58 |
-
need_weights: output attn_output_weights.
|
59 |
-
Default: `True`
|
60 |
-
Note: `needs_weight` defaults to `True`, but should be set to `False`
|
61 |
-
For best performance when attention weights are not nedeeded.
|
62 |
-
*Setting needs_weights to `True`
|
63 |
-
leads to a significant performance degradation.*
|
64 |
-
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
|
65 |
-
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
|
66 |
-
is_causal: If specified, applies a causal mask as attention mask, and ignores
|
67 |
-
attn_mask for computing scaled dot product attention.
|
68 |
-
Default: ``False``.
|
69 |
-
.. warning::
|
70 |
-
is_causal is provides a hint that the attn_mask is the
|
71 |
-
causal mask.Providing incorrect hints can result in
|
72 |
-
incorrect execution, including forward and backward
|
73 |
-
compatibility.
|
74 |
-
use_separate_proj_weight: the function accept the proj. weights for query, key,
|
75 |
-
and value in different forms. If false, in_proj_weight will be used, which is
|
76 |
-
a combination of q_proj_weight, k_proj_weight, v_proj_weight.
|
77 |
-
q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
|
78 |
-
static_k, static_v: static key and value used for attention operators.
|
79 |
-
average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
|
80 |
-
Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
|
81 |
-
when ``need_weights=True.``. Default: True
|
82 |
-
|
83 |
-
|
84 |
-
Shape:
|
85 |
-
Inputs:
|
86 |
-
- query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
|
87 |
-
the embedding dimension.
|
88 |
-
- key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
|
89 |
-
the embedding dimension.
|
90 |
-
- value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
|
91 |
-
the embedding dimension.
|
92 |
-
- key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
|
93 |
-
If a FloatTensor is provided, it will be directly added to the value.
|
94 |
-
If a BoolTensor is provided, the positions with the
|
95 |
-
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
96 |
-
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
|
97 |
-
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
|
98 |
-
S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
|
99 |
-
positions. If a BoolTensor is provided, positions with ``True``
|
100 |
-
are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
101 |
-
is provided, it will be added to the attention weight.
|
102 |
-
- static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
|
103 |
-
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
|
104 |
-
- static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
|
105 |
-
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
|
106 |
-
|
107 |
-
Outputs:
|
108 |
-
- attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
|
109 |
-
E is the embedding dimension.
|
110 |
-
- attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
|
111 |
-
attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
|
112 |
-
:math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
|
113 |
-
:math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
114 |
-
head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
|
115 |
-
"""
|
116 |
-
tens_ops = (
|
117 |
-
query,
|
118 |
-
key,
|
119 |
-
value,
|
120 |
-
in_proj_weight,
|
121 |
-
in_proj_bias,
|
122 |
-
bias_k,
|
123 |
-
bias_v,
|
124 |
-
out_proj_weight,
|
125 |
-
out_proj_bias,
|
126 |
-
)
|
127 |
-
if has_torch_function(tens_ops):
|
128 |
-
return handle_torch_function(
|
129 |
-
multi_head_attention_forward,
|
130 |
-
tens_ops,
|
131 |
-
query,
|
132 |
-
key,
|
133 |
-
value,
|
134 |
-
embed_dim_to_check,
|
135 |
-
num_heads,
|
136 |
-
in_proj_weight,
|
137 |
-
in_proj_bias,
|
138 |
-
bias_k,
|
139 |
-
bias_v,
|
140 |
-
add_zero_attn,
|
141 |
-
dropout_p,
|
142 |
-
out_proj_weight,
|
143 |
-
out_proj_bias,
|
144 |
-
training=training,
|
145 |
-
key_padding_mask=key_padding_mask,
|
146 |
-
need_weights=need_weights,
|
147 |
-
attn_mask=attn_mask,
|
148 |
-
is_causal=is_causal,
|
149 |
-
use_separate_proj_weight=use_separate_proj_weight,
|
150 |
-
q_proj_weight=q_proj_weight,
|
151 |
-
k_proj_weight=k_proj_weight,
|
152 |
-
v_proj_weight=v_proj_weight,
|
153 |
-
static_k=static_k,
|
154 |
-
static_v=static_v,
|
155 |
-
average_attn_weights=average_attn_weights,
|
156 |
-
cache=cache,
|
157 |
-
)
|
158 |
-
|
159 |
-
is_batched = _mha_shape_check(
|
160 |
-
query, key, value, key_padding_mask, attn_mask, num_heads
|
161 |
-
)
|
162 |
-
|
163 |
-
# For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
|
164 |
-
# is batched, run the computation and before returning squeeze the
|
165 |
-
# batch dimension so that the output doesn't carry this temporary batch dimension.
|
166 |
-
if not is_batched:
|
167 |
-
# unsqueeze if the input is unbatched
|
168 |
-
query = query.unsqueeze(1)
|
169 |
-
key = key.unsqueeze(1)
|
170 |
-
value = value.unsqueeze(1)
|
171 |
-
if key_padding_mask is not None:
|
172 |
-
key_padding_mask = key_padding_mask.unsqueeze(0)
|
173 |
-
|
174 |
-
# set up shape vars
|
175 |
-
tgt_len, bsz, embed_dim = query.shape
|
176 |
-
src_len, _, _ = key.shape
|
177 |
-
|
178 |
-
key_padding_mask = _canonical_mask(
|
179 |
-
mask=key_padding_mask,
|
180 |
-
mask_name="key_padding_mask",
|
181 |
-
other_type=_none_or_dtype(attn_mask),
|
182 |
-
other_name="attn_mask",
|
183 |
-
target_type=query.dtype,
|
184 |
-
)
|
185 |
-
|
186 |
-
if is_causal and attn_mask is None:
|
187 |
-
raise RuntimeError(
|
188 |
-
"Need attn_mask if specifying the is_causal hint. "
|
189 |
-
"You may use the Transformer module method "
|
190 |
-
"`generate_square_subsequent_mask` to create this mask."
|
191 |
-
)
|
192 |
-
|
193 |
-
if is_causal and key_padding_mask is None and not need_weights:
|
194 |
-
# when we have a kpm or need weights, we need attn_mask
|
195 |
-
# Otherwise, we use the is_causal hint go as is_causal
|
196 |
-
# indicator to SDPA.
|
197 |
-
attn_mask = None
|
198 |
-
else:
|
199 |
-
attn_mask = _canonical_mask(
|
200 |
-
mask=attn_mask,
|
201 |
-
mask_name="attn_mask",
|
202 |
-
other_type=None,
|
203 |
-
other_name="",
|
204 |
-
target_type=query.dtype,
|
205 |
-
check_other=False,
|
206 |
-
)
|
207 |
-
|
208 |
-
if key_padding_mask is not None:
|
209 |
-
# We have the attn_mask, and use that to merge kpm into it.
|
210 |
-
# Turn off use of is_causal hint, as the merged mask is no
|
211 |
-
# longer causal.
|
212 |
-
is_causal = False
|
213 |
-
|
214 |
-
assert (
|
215 |
-
embed_dim == embed_dim_to_check
|
216 |
-
), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
|
217 |
-
if isinstance(embed_dim, torch.Tensor):
|
218 |
-
# embed_dim can be a tensor when JIT tracing
|
219 |
-
head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
|
220 |
-
else:
|
221 |
-
head_dim = embed_dim // num_heads
|
222 |
-
assert (
|
223 |
-
head_dim * num_heads == embed_dim
|
224 |
-
), f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
|
225 |
-
if use_separate_proj_weight:
|
226 |
-
# allow MHA to have different embedding dimensions when separate projection weights are used
|
227 |
-
assert (
|
228 |
-
key.shape[:2] == value.shape[:2]
|
229 |
-
), f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
|
230 |
-
else:
|
231 |
-
assert (
|
232 |
-
key.shape == value.shape
|
233 |
-
), f"key shape {key.shape} does not match value shape {value.shape}"
|
234 |
-
|
235 |
-
#
|
236 |
-
# compute in-projection
|
237 |
-
#
|
238 |
-
if not use_separate_proj_weight:
|
239 |
-
assert (
|
240 |
-
in_proj_weight is not None
|
241 |
-
), "use_separate_proj_weight is False but in_proj_weight is None"
|
242 |
-
q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
|
243 |
-
else:
|
244 |
-
assert (
|
245 |
-
q_proj_weight is not None
|
246 |
-
), "use_separate_proj_weight is True but q_proj_weight is None"
|
247 |
-
assert (
|
248 |
-
k_proj_weight is not None
|
249 |
-
), "use_separate_proj_weight is True but k_proj_weight is None"
|
250 |
-
assert (
|
251 |
-
v_proj_weight is not None
|
252 |
-
), "use_separate_proj_weight is True but v_proj_weight is None"
|
253 |
-
if in_proj_bias is None:
|
254 |
-
b_q = b_k = b_v = None
|
255 |
-
else:
|
256 |
-
b_q, b_k, b_v = in_proj_bias.chunk(3)
|
257 |
-
q, k, v = _in_projection(
|
258 |
-
query,
|
259 |
-
key,
|
260 |
-
value,
|
261 |
-
q_proj_weight,
|
262 |
-
k_proj_weight,
|
263 |
-
v_proj_weight,
|
264 |
-
b_q,
|
265 |
-
b_k,
|
266 |
-
b_v,
|
267 |
-
)
|
268 |
-
if cache != None:
|
269 |
-
if cache["first_infer"] == 1:
|
270 |
-
cache["k"][cache["stage"]] = k
|
271 |
-
# print(0,cache["k"].shape)
|
272 |
-
cache["v"][cache["stage"]] = v
|
273 |
-
else: ###12个layer每个都要留自己的cache_kv
|
274 |
-
# print(1,cache["k"].shape)
|
275 |
-
cache["k"][cache["stage"]] = torch.cat(
|
276 |
-
[cache["k"][cache["stage"]], k], 0
|
277 |
-
) ##本来时序是1,但是proj的时候可能transpose了所以时序到0维了
|
278 |
-
cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]], v], 0)
|
279 |
-
# print(2, cache["k"].shape)
|
280 |
-
src_len = cache["k"][cache["stage"]].shape[0]
|
281 |
-
k = cache["k"][cache["stage"]]
|
282 |
-
v = cache["v"][cache["stage"]]
|
283 |
-
# if attn_mask is not None:
|
284 |
-
# attn_mask=attn_mask[-1:,]
|
285 |
-
# print(attn_mask.shape,attn_mask)
|
286 |
-
cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
|
287 |
-
# print(2333,cache)
|
288 |
-
# prep attention mask
|
289 |
-
|
290 |
-
attn_mask = _canonical_mask(
|
291 |
-
mask=attn_mask,
|
292 |
-
mask_name="attn_mask",
|
293 |
-
other_type=None,
|
294 |
-
other_name="",
|
295 |
-
target_type=q.dtype,
|
296 |
-
check_other=False,
|
297 |
-
)
|
298 |
-
|
299 |
-
if attn_mask is not None:
|
300 |
-
# ensure attn_mask's dim is 3
|
301 |
-
if attn_mask.dim() == 2:
|
302 |
-
correct_2d_size = (tgt_len, src_len)
|
303 |
-
if attn_mask.shape != correct_2d_size:
|
304 |
-
raise RuntimeError(
|
305 |
-
f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
|
306 |
-
)
|
307 |
-
attn_mask = attn_mask.unsqueeze(0)
|
308 |
-
elif attn_mask.dim() == 3:
|
309 |
-
correct_3d_size = (bsz * num_heads, tgt_len, src_len)
|
310 |
-
if attn_mask.shape != correct_3d_size:
|
311 |
-
raise RuntimeError(
|
312 |
-
f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
|
313 |
-
)
|
314 |
-
else:
|
315 |
-
raise RuntimeError(
|
316 |
-
f"attn_mask's dimension {attn_mask.dim()} is not supported"
|
317 |
-
)
|
318 |
-
|
319 |
-
# add bias along batch dimension (currently second)
|
320 |
-
if bias_k is not None and bias_v is not None:
|
321 |
-
assert static_k is None, "bias cannot be added to static key."
|
322 |
-
assert static_v is None, "bias cannot be added to static value."
|
323 |
-
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
324 |
-
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
325 |
-
if attn_mask is not None:
|
326 |
-
attn_mask = pad(attn_mask, (0, 1))
|
327 |
-
if key_padding_mask is not None:
|
328 |
-
key_padding_mask = pad(key_padding_mask, (0, 1))
|
329 |
-
else:
|
330 |
-
assert bias_k is None
|
331 |
-
assert bias_v is None
|
332 |
-
|
333 |
-
#
|
334 |
-
# reshape q, k, v for multihead attention and make em batch first
|
335 |
-
#
|
336 |
-
q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
|
337 |
-
if static_k is None:
|
338 |
-
k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
339 |
-
else:
|
340 |
-
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
341 |
-
assert (
|
342 |
-
static_k.size(0) == bsz * num_heads
|
343 |
-
), f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
|
344 |
-
assert (
|
345 |
-
static_k.size(2) == head_dim
|
346 |
-
), f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
|
347 |
-
k = static_k
|
348 |
-
if static_v is None:
|
349 |
-
v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
350 |
-
else:
|
351 |
-
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
352 |
-
assert (
|
353 |
-
static_v.size(0) == bsz * num_heads
|
354 |
-
), f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
|
355 |
-
assert (
|
356 |
-
static_v.size(2) == head_dim
|
357 |
-
), f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
|
358 |
-
v = static_v
|
359 |
-
|
360 |
-
# add zero attention along batch dimension (now first)
|
361 |
-
if add_zero_attn:
|
362 |
-
zero_attn_shape = (bsz * num_heads, 1, head_dim)
|
363 |
-
k = torch.cat(
|
364 |
-
[k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1
|
365 |
-
)
|
366 |
-
v = torch.cat(
|
367 |
-
[v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1
|
368 |
-
)
|
369 |
-
if attn_mask is not None:
|
370 |
-
attn_mask = pad(attn_mask, (0, 1))
|
371 |
-
if key_padding_mask is not None:
|
372 |
-
key_padding_mask = pad(key_padding_mask, (0, 1))
|
373 |
-
|
374 |
-
# update source sequence length after adjustments
|
375 |
-
src_len = k.size(1)
|
376 |
-
|
377 |
-
# merge key padding and attention masks
|
378 |
-
if key_padding_mask is not None:
|
379 |
-
assert key_padding_mask.shape == (
|
380 |
-
bsz,
|
381 |
-
src_len,
|
382 |
-
), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
|
383 |
-
key_padding_mask = (
|
384 |
-
key_padding_mask.view(bsz, 1, 1, src_len)
|
385 |
-
.expand(-1, num_heads, -1, -1)
|
386 |
-
.reshape(bsz * num_heads, 1, src_len)
|
387 |
-
)
|
388 |
-
if attn_mask is None:
|
389 |
-
attn_mask = key_padding_mask
|
390 |
-
else:
|
391 |
-
attn_mask = attn_mask + key_padding_mask
|
392 |
-
|
393 |
-
# adjust dropout probability
|
394 |
-
if not training:
|
395 |
-
dropout_p = 0.0
|
396 |
-
|
397 |
-
#
|
398 |
-
# (deep breath) calculate attention and out projection
|
399 |
-
#
|
400 |
-
|
401 |
-
if need_weights:
|
402 |
-
B, Nt, E = q.shape
|
403 |
-
q_scaled = q / math.sqrt(E)
|
404 |
-
|
405 |
-
assert not (
|
406 |
-
is_causal and attn_mask is None
|
407 |
-
), "FIXME: is_causal not implemented for need_weights"
|
408 |
-
|
409 |
-
if attn_mask is not None:
|
410 |
-
attn_output_weights = torch.baddbmm(
|
411 |
-
attn_mask, q_scaled, k.transpose(-2, -1)
|
412 |
-
)
|
413 |
-
else:
|
414 |
-
attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
|
415 |
-
attn_output_weights = softmax(attn_output_weights, dim=-1)
|
416 |
-
if dropout_p > 0.0:
|
417 |
-
attn_output_weights = dropout(attn_output_weights, p=dropout_p)
|
418 |
-
|
419 |
-
attn_output = torch.bmm(attn_output_weights, v)
|
420 |
-
|
421 |
-
attn_output = (
|
422 |
-
attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
|
423 |
-
)
|
424 |
-
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
425 |
-
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
426 |
-
|
427 |
-
# optionally average attention weights over heads
|
428 |
-
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
429 |
-
if average_attn_weights:
|
430 |
-
attn_output_weights = attn_output_weights.mean(dim=1)
|
431 |
-
|
432 |
-
if not is_batched:
|
433 |
-
# squeeze the output if input was unbatched
|
434 |
-
attn_output = attn_output.squeeze(1)
|
435 |
-
attn_output_weights = attn_output_weights.squeeze(0)
|
436 |
-
return attn_output, attn_output_weights
|
437 |
-
else:
|
438 |
-
# attn_mask can be either (L,S) or (N*num_heads, L, S)
|
439 |
-
# if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
|
440 |
-
# in order to match the input for SDPA of (N, num_heads, L, S)
|
441 |
-
if attn_mask is not None:
|
442 |
-
if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
|
443 |
-
attn_mask = attn_mask.unsqueeze(0)
|
444 |
-
else:
|
445 |
-
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
|
446 |
-
|
447 |
-
q = q.view(bsz, num_heads, tgt_len, head_dim)
|
448 |
-
k = k.view(bsz, num_heads, src_len, head_dim)
|
449 |
-
v = v.view(bsz, num_heads, src_len, head_dim)
|
450 |
-
|
451 |
-
# with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
452 |
-
attn_output = scaled_dot_product_attention(
|
453 |
-
q, k, v, attn_mask, dropout_p, is_causal
|
454 |
-
)
|
455 |
-
|
456 |
-
attn_output = (
|
457 |
-
attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
|
458 |
-
)
|
459 |
-
|
460 |
-
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
461 |
-
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
462 |
-
if not is_batched:
|
463 |
-
# squeeze the output if input was unbatched
|
464 |
-
attn_output = attn_output.squeeze(1)
|
465 |
-
return attn_output, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/patched_mha_with_cache_onnx.py
DELETED
@@ -1,92 +0,0 @@
|
|
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 |
-
|
9 |
-
def multi_head_attention_forward_patched(
|
10 |
-
query,
|
11 |
-
key,
|
12 |
-
value,
|
13 |
-
embed_dim_to_check: int,
|
14 |
-
num_heads: int,
|
15 |
-
in_proj_weight,
|
16 |
-
in_proj_bias: Optional[Tensor],
|
17 |
-
bias_k: Optional[Tensor],
|
18 |
-
bias_v: Optional[Tensor],
|
19 |
-
add_zero_attn: bool,
|
20 |
-
dropout_p: float,
|
21 |
-
out_proj_weight: Tensor,
|
22 |
-
out_proj_bias: Optional[Tensor],
|
23 |
-
training: bool = True,
|
24 |
-
key_padding_mask: Optional[Tensor] = None,
|
25 |
-
need_weights: bool = True,
|
26 |
-
attn_mask: Optional[Tensor] = None,
|
27 |
-
use_separate_proj_weight: bool = False,
|
28 |
-
q_proj_weight: Optional[Tensor] = None,
|
29 |
-
k_proj_weight: Optional[Tensor] = None,
|
30 |
-
v_proj_weight: Optional[Tensor] = None,
|
31 |
-
static_k: Optional[Tensor] = None,
|
32 |
-
static_v: Optional[Tensor] = None,
|
33 |
-
average_attn_weights: bool = True,
|
34 |
-
is_causal: bool = False,
|
35 |
-
cache=None,
|
36 |
-
) -> Tuple[Tensor, Optional[Tensor]]:
|
37 |
-
|
38 |
-
# set up shape vars
|
39 |
-
_, _, embed_dim = query.shape
|
40 |
-
attn_mask = _canonical_mask(
|
41 |
-
mask=attn_mask,
|
42 |
-
mask_name="attn_mask",
|
43 |
-
other_type=None,
|
44 |
-
other_name="",
|
45 |
-
target_type=query.dtype,
|
46 |
-
check_other=False,
|
47 |
-
)
|
48 |
-
head_dim = embed_dim // num_heads
|
49 |
-
|
50 |
-
proj_qkv = linear(query, in_proj_weight, in_proj_bias)
|
51 |
-
proj_qkv = proj_qkv.unflatten(-1, (3, query.size(-1))).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
|
52 |
-
q, k, v = proj_qkv[0], proj_qkv[1], proj_qkv[2]
|
53 |
-
|
54 |
-
if cache["first_infer"] == 1:
|
55 |
-
cache["k"][cache["stage"]] = k
|
56 |
-
cache["v"][cache["stage"]] = v
|
57 |
-
else:
|
58 |
-
cache["k"][cache["stage"]] = torch.cat([cache["k"][cache["stage"]][:-1], k], 0)
|
59 |
-
cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]][:-1], v], 0)
|
60 |
-
k = cache["k"][cache["stage"]]
|
61 |
-
v = cache["v"][cache["stage"]]
|
62 |
-
cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
|
63 |
-
|
64 |
-
attn_mask = _canonical_mask(
|
65 |
-
mask=attn_mask,
|
66 |
-
mask_name="attn_mask",
|
67 |
-
other_type=None,
|
68 |
-
other_name="",
|
69 |
-
target_type=q.dtype,
|
70 |
-
check_other=False,
|
71 |
-
)
|
72 |
-
attn_mask = attn_mask.unsqueeze(0)
|
73 |
-
|
74 |
-
q = q.view(-1, num_heads, head_dim).transpose(0, 1)
|
75 |
-
k = k.view(-1, num_heads, head_dim).transpose(0, 1)
|
76 |
-
v = v.view(-1, num_heads, head_dim).transpose(0, 1)
|
77 |
-
|
78 |
-
dropout_p = 0.0
|
79 |
-
attn_mask = attn_mask.unsqueeze(0)
|
80 |
-
q = q.view(num_heads, -1, head_dim).unsqueeze(0)
|
81 |
-
k = k.view(num_heads, -1, head_dim).unsqueeze(0)
|
82 |
-
v = v.view(num_heads, -1, head_dim).unsqueeze(0)
|
83 |
-
attn_output = scaled_dot_product_attention(
|
84 |
-
q, k, v, attn_mask, dropout_p, is_causal
|
85 |
-
)
|
86 |
-
attn_output = (
|
87 |
-
attn_output.permute(2, 0, 1, 3).contiguous().view(-1, embed_dim)
|
88 |
-
)
|
89 |
-
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
90 |
-
attn_output = attn_output.view(-1, 1, attn_output.size(1))
|
91 |
-
|
92 |
-
return attn_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/scaling.py
DELETED
@@ -1,335 +0,0 @@
|
|
1 |
-
# Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
|
2 |
-
#
|
3 |
-
# See ../../../../LICENSE for clarification regarding multiple authors
|
4 |
-
#
|
5 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
-
# you may not use this file except in compliance with the License.
|
7 |
-
# You may obtain a copy of the License at
|
8 |
-
#
|
9 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
-
#
|
11 |
-
# Unless required by applicable law or agreed to in writing, software
|
12 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
-
# See the License for the specific language governing permissions and
|
15 |
-
# limitations under the License.
|
16 |
-
import logging
|
17 |
-
import math
|
18 |
-
import random
|
19 |
-
from typing import Optional
|
20 |
-
from typing import Tuple
|
21 |
-
from typing import Union
|
22 |
-
|
23 |
-
import torch
|
24 |
-
import torch.nn as nn
|
25 |
-
from torch import Tensor
|
26 |
-
|
27 |
-
|
28 |
-
class DoubleSwishFunction(torch.autograd.Function):
|
29 |
-
"""
|
30 |
-
double_swish(x) = x * torch.sigmoid(x-1)
|
31 |
-
This is a definition, originally motivated by its close numerical
|
32 |
-
similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
|
33 |
-
|
34 |
-
Memory-efficient derivative computation:
|
35 |
-
double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
|
36 |
-
double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
|
37 |
-
Now, s'(x) = s(x) * (1-s(x)).
|
38 |
-
double_swish'(x) = x * s'(x) + s(x).
|
39 |
-
= x * s(x) * (1-s(x)) + s(x).
|
40 |
-
= double_swish(x) * (1-s(x)) + s(x)
|
41 |
-
... so we just need to remember s(x) but not x itself.
|
42 |
-
"""
|
43 |
-
|
44 |
-
@staticmethod
|
45 |
-
def forward(ctx, x: Tensor) -> Tensor:
|
46 |
-
requires_grad = x.requires_grad
|
47 |
-
x_dtype = x.dtype
|
48 |
-
if x.dtype == torch.float16:
|
49 |
-
x = x.to(torch.float32)
|
50 |
-
|
51 |
-
s = torch.sigmoid(x - 1.0)
|
52 |
-
y = x * s
|
53 |
-
|
54 |
-
if requires_grad:
|
55 |
-
deriv = y * (1 - s) + s
|
56 |
-
# notes on derivative of x * sigmoid(x - 1):
|
57 |
-
# https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
|
58 |
-
# min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
|
59 |
-
# max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
|
60 |
-
# the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
|
61 |
-
# floors), should be expectation-preserving.
|
62 |
-
floor = -0.043637
|
63 |
-
ceil = 1.2
|
64 |
-
d_scaled = (deriv - floor) * (255.0 / (ceil - floor)) + torch.rand_like(
|
65 |
-
deriv
|
66 |
-
)
|
67 |
-
if __name__ == "__main__":
|
68 |
-
# for self-testing only.
|
69 |
-
assert d_scaled.min() >= 0.0
|
70 |
-
assert d_scaled.max() < 256.0
|
71 |
-
d_int = d_scaled.to(torch.uint8)
|
72 |
-
ctx.save_for_backward(d_int)
|
73 |
-
if x.dtype == torch.float16 or torch.is_autocast_enabled():
|
74 |
-
y = y.to(torch.float16)
|
75 |
-
return y
|
76 |
-
|
77 |
-
@staticmethod
|
78 |
-
def backward(ctx, y_grad: Tensor) -> Tensor:
|
79 |
-
(d,) = ctx.saved_tensors
|
80 |
-
# the same constants as used in forward pass.
|
81 |
-
floor = -0.043637
|
82 |
-
ceil = 1.2
|
83 |
-
d = d * ((ceil - floor) / 255.0) + floor
|
84 |
-
return y_grad * d
|
85 |
-
|
86 |
-
|
87 |
-
class DoubleSwish(torch.nn.Module):
|
88 |
-
def forward(self, x: Tensor) -> Tensor:
|
89 |
-
"""Return double-swish activation function which is an approximation to Swish(Swish(x)),
|
90 |
-
that we approximate closely with x * sigmoid(x-1).
|
91 |
-
"""
|
92 |
-
if torch.jit.is_scripting() or torch.jit.is_tracing():
|
93 |
-
return x * torch.sigmoid(x - 1.0)
|
94 |
-
return DoubleSwishFunction.apply(x)
|
95 |
-
|
96 |
-
|
97 |
-
class ActivationBalancerFunction(torch.autograd.Function):
|
98 |
-
@staticmethod
|
99 |
-
def forward(
|
100 |
-
ctx,
|
101 |
-
x: Tensor,
|
102 |
-
scale_factor: Tensor,
|
103 |
-
sign_factor: Optional[Tensor],
|
104 |
-
channel_dim: int,
|
105 |
-
) -> Tensor:
|
106 |
-
if channel_dim < 0:
|
107 |
-
channel_dim += x.ndim
|
108 |
-
ctx.channel_dim = channel_dim
|
109 |
-
xgt0 = x > 0
|
110 |
-
if sign_factor is None:
|
111 |
-
ctx.save_for_backward(xgt0, scale_factor)
|
112 |
-
else:
|
113 |
-
ctx.save_for_backward(xgt0, scale_factor, sign_factor)
|
114 |
-
return x
|
115 |
-
|
116 |
-
@staticmethod
|
117 |
-
def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
|
118 |
-
if len(ctx.saved_tensors) == 3:
|
119 |
-
xgt0, scale_factor, sign_factor = ctx.saved_tensors
|
120 |
-
for _ in range(ctx.channel_dim, x_grad.ndim - 1):
|
121 |
-
scale_factor = scale_factor.unsqueeze(-1)
|
122 |
-
sign_factor = sign_factor.unsqueeze(-1)
|
123 |
-
factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
|
124 |
-
else:
|
125 |
-
xgt0, scale_factor = ctx.saved_tensors
|
126 |
-
for _ in range(ctx.channel_dim, x_grad.ndim - 1):
|
127 |
-
scale_factor = scale_factor.unsqueeze(-1)
|
128 |
-
factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
|
129 |
-
neg_delta_grad = x_grad.abs() * factor
|
130 |
-
return (
|
131 |
-
x_grad - neg_delta_grad,
|
132 |
-
None,
|
133 |
-
None,
|
134 |
-
None,
|
135 |
-
)
|
136 |
-
|
137 |
-
|
138 |
-
def _compute_scale_factor(
|
139 |
-
x: Tensor,
|
140 |
-
channel_dim: int,
|
141 |
-
min_abs: float,
|
142 |
-
max_abs: float,
|
143 |
-
gain_factor: float,
|
144 |
-
max_factor: float,
|
145 |
-
) -> Tensor:
|
146 |
-
if channel_dim < 0:
|
147 |
-
channel_dim += x.ndim
|
148 |
-
sum_dims = [d for d in range(x.ndim) if d != channel_dim]
|
149 |
-
x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
|
150 |
-
|
151 |
-
if min_abs == 0.0:
|
152 |
-
below_threshold = 0.0
|
153 |
-
else:
|
154 |
-
# below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
|
155 |
-
# x_abs)_mean , min_abs.
|
156 |
-
below_threshold = ((min_abs - x_abs_mean) * (gain_factor / min_abs)).clamp(
|
157 |
-
min=0, max=max_factor
|
158 |
-
)
|
159 |
-
|
160 |
-
above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(
|
161 |
-
min=0, max=max_factor
|
162 |
-
)
|
163 |
-
|
164 |
-
return below_threshold - above_threshold
|
165 |
-
|
166 |
-
|
167 |
-
def _compute_sign_factor(
|
168 |
-
x: Tensor,
|
169 |
-
channel_dim: int,
|
170 |
-
min_positive: float,
|
171 |
-
max_positive: float,
|
172 |
-
gain_factor: float,
|
173 |
-
max_factor: float,
|
174 |
-
) -> Tensor:
|
175 |
-
if channel_dim < 0:
|
176 |
-
channel_dim += x.ndim
|
177 |
-
sum_dims = [d for d in range(x.ndim) if d != channel_dim]
|
178 |
-
proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
|
179 |
-
if min_positive == 0.0:
|
180 |
-
factor1 = 0.0
|
181 |
-
else:
|
182 |
-
# 0 if proportion_positive >= min_positive, else can be
|
183 |
-
# as large as max_factor.
|
184 |
-
factor1 = (
|
185 |
-
(min_positive - proportion_positive) * (gain_factor / min_positive)
|
186 |
-
).clamp_(min=0, max=max_factor)
|
187 |
-
|
188 |
-
if max_positive == 1.0:
|
189 |
-
factor2 = 0.0
|
190 |
-
else:
|
191 |
-
# 0 if self.proportion_positive <= max_positive, else can be
|
192 |
-
# as large as -max_factor.
|
193 |
-
factor2 = (
|
194 |
-
(proportion_positive - max_positive) * (gain_factor / (1.0 - max_positive))
|
195 |
-
).clamp_(min=0, max=max_factor)
|
196 |
-
sign_factor = factor1 - factor2
|
197 |
-
# require min_positive != 0 or max_positive != 1:
|
198 |
-
assert not isinstance(sign_factor, float)
|
199 |
-
return sign_factor
|
200 |
-
|
201 |
-
|
202 |
-
class ActivationBalancer(torch.nn.Module):
|
203 |
-
"""
|
204 |
-
Modifies the backpropped derivatives of a function to try to encourage, for
|
205 |
-
each channel, that it is positive at least a proportion `threshold` of the
|
206 |
-
time. It does this by multiplying negative derivative values by up to
|
207 |
-
(1+max_factor), and positive derivative values by up to (1-max_factor),
|
208 |
-
interpolated from 1 at the threshold to those extremal values when none
|
209 |
-
of the inputs are positive.
|
210 |
-
|
211 |
-
Args:
|
212 |
-
num_channels: the number of channels
|
213 |
-
channel_dim: the dimension/axis corresponding to the channel, e.g.
|
214 |
-
-1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
|
215 |
-
min_positive: the minimum, per channel, of the proportion of the time
|
216 |
-
that (x > 0), below which we start to modify the derivatives.
|
217 |
-
max_positive: the maximum, per channel, of the proportion of the time
|
218 |
-
that (x > 0), above which we start to modify the derivatives.
|
219 |
-
max_factor: the maximum factor by which we modify the derivatives for
|
220 |
-
either the sign constraint or the magnitude constraint;
|
221 |
-
e.g. with max_factor=0.02, the the derivatives would be multiplied by
|
222 |
-
values in the range [0.98..1.02].
|
223 |
-
sign_gain_factor: determines the 'gain' with which we increase the
|
224 |
-
change in gradient once the constraints on min_positive and max_positive
|
225 |
-
are violated.
|
226 |
-
scale_gain_factor: determines the 'gain' with which we increase the
|
227 |
-
change in gradient once the constraints on min_abs and max_abs
|
228 |
-
are violated.
|
229 |
-
min_abs: the minimum average-absolute-value difference from the mean
|
230 |
-
value per channel, which we allow, before we start to modify
|
231 |
-
the derivatives to prevent this.
|
232 |
-
max_abs: the maximum average-absolute-value difference from the mean
|
233 |
-
value per channel, which we allow, before we start to modify
|
234 |
-
the derivatives to prevent this.
|
235 |
-
min_prob: determines the minimum probability with which we modify the
|
236 |
-
gradients for the {min,max}_positive and {min,max}_abs constraints,
|
237 |
-
on each forward(). This is done randomly to prevent all layers
|
238 |
-
from doing it at the same time. Early in training we may use
|
239 |
-
higher probabilities than this; it will decay to this value.
|
240 |
-
"""
|
241 |
-
|
242 |
-
def __init__(
|
243 |
-
self,
|
244 |
-
num_channels: int,
|
245 |
-
channel_dim: int,
|
246 |
-
min_positive: float = 0.05,
|
247 |
-
max_positive: float = 0.95,
|
248 |
-
max_factor: float = 0.04,
|
249 |
-
sign_gain_factor: float = 0.01,
|
250 |
-
scale_gain_factor: float = 0.02,
|
251 |
-
min_abs: float = 0.2,
|
252 |
-
max_abs: float = 100.0,
|
253 |
-
min_prob: float = 0.1,
|
254 |
-
):
|
255 |
-
super(ActivationBalancer, self).__init__()
|
256 |
-
self.num_channels = num_channels
|
257 |
-
self.channel_dim = channel_dim
|
258 |
-
self.min_positive = min_positive
|
259 |
-
self.max_positive = max_positive
|
260 |
-
self.max_factor = max_factor
|
261 |
-
self.min_abs = min_abs
|
262 |
-
self.max_abs = max_abs
|
263 |
-
self.min_prob = min_prob
|
264 |
-
self.sign_gain_factor = sign_gain_factor
|
265 |
-
self.scale_gain_factor = scale_gain_factor
|
266 |
-
|
267 |
-
# count measures how many times the forward() function has been called.
|
268 |
-
# We occasionally sync this to a tensor called `count`, that exists to
|
269 |
-
# make sure it is synced to disk when we load and save the model.
|
270 |
-
self.cpu_count = 0
|
271 |
-
self.register_buffer("count", torch.tensor(0, dtype=torch.int64))
|
272 |
-
|
273 |
-
def forward(self, x: Tensor) -> Tensor:
|
274 |
-
if torch.jit.is_scripting() or not x.requires_grad or torch.jit.is_tracing():
|
275 |
-
return _no_op(x)
|
276 |
-
|
277 |
-
count = self.cpu_count
|
278 |
-
self.cpu_count += 1
|
279 |
-
|
280 |
-
if random.random() < 0.01:
|
281 |
-
# Occasionally sync self.cpu_count with self.count.
|
282 |
-
# count affects the decay of 'prob'. don't do this on every iter,
|
283 |
-
# because syncing with the GPU is slow.
|
284 |
-
self.cpu_count = max(self.cpu_count, self.count.item())
|
285 |
-
self.count.fill_(self.cpu_count)
|
286 |
-
|
287 |
-
# the prob of doing some work exponentially decreases from 0.5 till it hits
|
288 |
-
# a floor at min_prob (==0.1, by default)
|
289 |
-
prob = max(self.min_prob, 0.5 ** (1 + (count / 4000.0)))
|
290 |
-
|
291 |
-
if random.random() < prob:
|
292 |
-
sign_gain_factor = 0.5
|
293 |
-
if self.min_positive != 0.0 or self.max_positive != 1.0:
|
294 |
-
sign_factor = _compute_sign_factor(
|
295 |
-
x,
|
296 |
-
self.channel_dim,
|
297 |
-
self.min_positive,
|
298 |
-
self.max_positive,
|
299 |
-
gain_factor=self.sign_gain_factor / prob,
|
300 |
-
max_factor=self.max_factor,
|
301 |
-
)
|
302 |
-
else:
|
303 |
-
sign_factor = None
|
304 |
-
|
305 |
-
scale_factor = _compute_scale_factor(
|
306 |
-
x.detach(),
|
307 |
-
self.channel_dim,
|
308 |
-
min_abs=self.min_abs,
|
309 |
-
max_abs=self.max_abs,
|
310 |
-
gain_factor=self.scale_gain_factor / prob,
|
311 |
-
max_factor=self.max_factor,
|
312 |
-
)
|
313 |
-
return ActivationBalancerFunction.apply(
|
314 |
-
x,
|
315 |
-
scale_factor,
|
316 |
-
sign_factor,
|
317 |
-
self.channel_dim,
|
318 |
-
)
|
319 |
-
else:
|
320 |
-
return _no_op(x)
|
321 |
-
|
322 |
-
|
323 |
-
def BalancedDoubleSwish(
|
324 |
-
d_model, channel_dim=-1, max_abs=10.0, min_prob=0.25
|
325 |
-
) -> nn.Sequential:
|
326 |
-
"""
|
327 |
-
ActivationBalancer -> DoubleSwish
|
328 |
-
"""
|
329 |
-
balancer = ActivationBalancer(
|
330 |
-
d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob
|
331 |
-
)
|
332 |
-
return nn.Sequential(
|
333 |
-
balancer,
|
334 |
-
DoubleSwish(),
|
335 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/transformer.py
DELETED
@@ -1,378 +0,0 @@
|
|
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(
|
46 |
-
torch.empty(self.normalized_shape, **factory_kwargs)
|
47 |
-
)
|
48 |
-
self.bias = nn.Parameter(
|
49 |
-
torch.empty(self.normalized_shape, **factory_kwargs)
|
50 |
-
)
|
51 |
-
else:
|
52 |
-
self.register_parameter("weight", None)
|
53 |
-
self.register_parameter("bias", None)
|
54 |
-
|
55 |
-
self.reset_parameters()
|
56 |
-
|
57 |
-
def reset_parameters(self) -> None:
|
58 |
-
if self.elementwise_affine:
|
59 |
-
nn.init.ones_(self.weight)
|
60 |
-
nn.init.zeros_(self.bias)
|
61 |
-
|
62 |
-
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
63 |
-
if isinstance(input, tuple):
|
64 |
-
input, embedding = input
|
65 |
-
return (
|
66 |
-
F.layer_norm(
|
67 |
-
input,
|
68 |
-
self.normalized_shape,
|
69 |
-
self.weight,
|
70 |
-
self.bias,
|
71 |
-
self.eps,
|
72 |
-
),
|
73 |
-
embedding,
|
74 |
-
)
|
75 |
-
|
76 |
-
assert embedding is None
|
77 |
-
return F.layer_norm(
|
78 |
-
input, self.normalized_shape, self.weight, self.bias, self.eps
|
79 |
-
)
|
80 |
-
|
81 |
-
def extra_repr(self) -> str:
|
82 |
-
return (
|
83 |
-
"{normalized_shape}, eps={eps}, "
|
84 |
-
"elementwise_affine={elementwise_affine}".format(**self.__dict__)
|
85 |
-
)
|
86 |
-
|
87 |
-
|
88 |
-
class IdentityNorm(nn.Module):
|
89 |
-
def __init__(
|
90 |
-
self,
|
91 |
-
d_model: int,
|
92 |
-
eps: float = 1e-5,
|
93 |
-
device=None,
|
94 |
-
dtype=None,
|
95 |
-
) -> None:
|
96 |
-
super(IdentityNorm, self).__init__()
|
97 |
-
|
98 |
-
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
99 |
-
if isinstance(input, tuple):
|
100 |
-
return input
|
101 |
-
|
102 |
-
assert embedding is None
|
103 |
-
return input
|
104 |
-
|
105 |
-
|
106 |
-
class TransformerEncoder(nn.Module):
|
107 |
-
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
|
108 |
-
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
|
109 |
-
|
110 |
-
Args:
|
111 |
-
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
|
112 |
-
num_layers: the number of sub-encoder-layers in the encoder (required).
|
113 |
-
norm: the layer normalization component (optional).
|
114 |
-
enable_nested_tensor: if True, input will automatically convert to nested tensor
|
115 |
-
(and convert back on output). This will improve the overall performance of
|
116 |
-
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
|
117 |
-
|
118 |
-
Examples::
|
119 |
-
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
|
120 |
-
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
|
121 |
-
>>> src = torch.rand(10, 32, 512)
|
122 |
-
>>> out = transformer_encoder(src)
|
123 |
-
"""
|
124 |
-
__constants__ = ["norm"]
|
125 |
-
|
126 |
-
def __init__(self, encoder_layer, num_layers, norm=None):
|
127 |
-
super(TransformerEncoder, self).__init__()
|
128 |
-
self.layers = _get_clones(encoder_layer, num_layers)
|
129 |
-
self.num_layers = num_layers
|
130 |
-
self.norm = norm
|
131 |
-
|
132 |
-
def forward(
|
133 |
-
self,
|
134 |
-
src: Tensor,
|
135 |
-
mask: Optional[Tensor] = None,
|
136 |
-
src_key_padding_mask: Optional[Tensor] = None,
|
137 |
-
return_layer_states: bool = False,
|
138 |
-
cache=None,
|
139 |
-
) -> Tensor:
|
140 |
-
r"""Pass the input through the encoder layers in turn.
|
141 |
-
|
142 |
-
Args:
|
143 |
-
src: the sequence to the encoder (required).
|
144 |
-
mask: the mask for the src sequence (optional).
|
145 |
-
src_key_padding_mask: the mask for the src keys per batch (optional).
|
146 |
-
return_layer_states: return layers' state (optional).
|
147 |
-
|
148 |
-
Shape:
|
149 |
-
see the docs in Transformer class.
|
150 |
-
"""
|
151 |
-
if return_layer_states:
|
152 |
-
layer_states = [] # layers' output
|
153 |
-
output = src
|
154 |
-
for mod in self.layers:
|
155 |
-
output = mod(
|
156 |
-
output,
|
157 |
-
src_mask=mask,
|
158 |
-
src_key_padding_mask=src_key_padding_mask,
|
159 |
-
cache=cache,
|
160 |
-
)
|
161 |
-
layer_states.append(output[0])
|
162 |
-
|
163 |
-
if self.norm is not None:
|
164 |
-
output = self.norm(output)
|
165 |
-
|
166 |
-
return layer_states, output
|
167 |
-
|
168 |
-
output = src
|
169 |
-
for mod in self.layers:
|
170 |
-
output = mod(
|
171 |
-
output,
|
172 |
-
src_mask=mask,
|
173 |
-
src_key_padding_mask=src_key_padding_mask,
|
174 |
-
cache=cache,
|
175 |
-
)
|
176 |
-
|
177 |
-
if self.norm is not None:
|
178 |
-
output = self.norm(output)
|
179 |
-
|
180 |
-
return output
|
181 |
-
|
182 |
-
|
183 |
-
class TransformerEncoderLayer(nn.Module):
|
184 |
-
__constants__ = ["batch_first", "norm_first"]
|
185 |
-
|
186 |
-
def __init__(
|
187 |
-
self,
|
188 |
-
d_model: int,
|
189 |
-
nhead: int,
|
190 |
-
dim_feedforward: int = 2048,
|
191 |
-
dropout: float = 0.1,
|
192 |
-
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
193 |
-
batch_first: bool = False,
|
194 |
-
norm_first: bool = False,
|
195 |
-
device=None,
|
196 |
-
dtype=None,
|
197 |
-
linear1_self_attention_cls: nn.Module = nn.Linear,
|
198 |
-
linear2_self_attention_cls: nn.Module = nn.Linear,
|
199 |
-
linear1_feedforward_cls: nn.Module = nn.Linear,
|
200 |
-
linear2_feedforward_cls: nn.Module = nn.Linear,
|
201 |
-
layer_norm_cls: nn.Module = LayerNorm,
|
202 |
-
layer_norm_eps: float = 1e-5,
|
203 |
-
adaptive_layer_norm=False,
|
204 |
-
) -> None:
|
205 |
-
factory_kwargs = {"device": device, "dtype": dtype}
|
206 |
-
super(TransformerEncoderLayer, self).__init__()
|
207 |
-
# print(233333333333,d_model,nhead)
|
208 |
-
# import os
|
209 |
-
# os._exit(2333333)
|
210 |
-
self.self_attn = MultiheadAttention(
|
211 |
-
d_model, # 512 16
|
212 |
-
nhead,
|
213 |
-
dropout=dropout,
|
214 |
-
batch_first=batch_first,
|
215 |
-
linear1_cls=linear1_self_attention_cls,
|
216 |
-
linear2_cls=linear2_self_attention_cls,
|
217 |
-
**factory_kwargs,
|
218 |
-
)
|
219 |
-
|
220 |
-
# Implementation of Feedforward model
|
221 |
-
self.linear1 = linear1_feedforward_cls(
|
222 |
-
d_model, dim_feedforward, **factory_kwargs
|
223 |
-
)
|
224 |
-
self.dropout = nn.Dropout(dropout)
|
225 |
-
self.linear2 = linear2_feedforward_cls(
|
226 |
-
dim_feedforward, d_model, **factory_kwargs
|
227 |
-
)
|
228 |
-
|
229 |
-
self.norm_first = norm_first
|
230 |
-
self.dropout1 = nn.Dropout(dropout)
|
231 |
-
self.dropout2 = nn.Dropout(dropout)
|
232 |
-
|
233 |
-
# Legacy string support for activation function.
|
234 |
-
if isinstance(activation, str):
|
235 |
-
activation = _get_activation_fn(activation)
|
236 |
-
elif isinstance(activation, partial):
|
237 |
-
activation = activation(d_model)
|
238 |
-
elif activation == BalancedDoubleSwish:
|
239 |
-
activation = BalancedDoubleSwish(d_model)
|
240 |
-
|
241 |
-
# # We can't test self.activation in forward() in TorchScript,
|
242 |
-
# # so stash some information about it instead.
|
243 |
-
# if activation is F.relu or isinstance(activation, torch.nn.ReLU):
|
244 |
-
# self.activation_relu_or_gelu = 1
|
245 |
-
# elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
|
246 |
-
# self.activation_relu_or_gelu = 2
|
247 |
-
# else:
|
248 |
-
# self.activation_relu_or_gelu = 0
|
249 |
-
self.activation = activation
|
250 |
-
|
251 |
-
norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
252 |
-
if layer_norm_cls == IdentityNorm:
|
253 |
-
norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
254 |
-
else:
|
255 |
-
norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
256 |
-
|
257 |
-
if adaptive_layer_norm:
|
258 |
-
self.norm1 = AdaptiveLayerNorm(d_model, norm1)
|
259 |
-
self.norm2 = AdaptiveLayerNorm(d_model, norm2)
|
260 |
-
else:
|
261 |
-
self.norm1 = norm1
|
262 |
-
self.norm2 = norm2
|
263 |
-
|
264 |
-
def __setstate__(self, state):
|
265 |
-
super(TransformerEncoderLayer, self).__setstate__(state)
|
266 |
-
if not hasattr(self, "activation"):
|
267 |
-
self.activation = F.relu
|
268 |
-
|
269 |
-
def forward(
|
270 |
-
self,
|
271 |
-
src: Tensor,
|
272 |
-
src_mask: Optional[Tensor] = None,
|
273 |
-
src_key_padding_mask: Optional[Tensor] = None,
|
274 |
-
cache=None,
|
275 |
-
) -> Tensor:
|
276 |
-
r"""Pass the input through the encoder layer.
|
277 |
-
|
278 |
-
Args:
|
279 |
-
src: the sequence to the encoder layer (required).
|
280 |
-
src_mask: the mask for the src sequence (optional).
|
281 |
-
src_key_padding_mask: the mask for the src keys per batch (optional).
|
282 |
-
|
283 |
-
Shape:
|
284 |
-
see the docs in Transformer class.
|
285 |
-
"""
|
286 |
-
x, stage_embedding = src, None
|
287 |
-
is_src_tuple = False
|
288 |
-
if isinstance(src, tuple):
|
289 |
-
x, stage_embedding = src
|
290 |
-
is_src_tuple = True
|
291 |
-
|
292 |
-
if src_key_padding_mask is not None:
|
293 |
-
_skpm_dtype = src_key_padding_mask.dtype
|
294 |
-
if _skpm_dtype != torch.bool and not torch.is_floating_point(
|
295 |
-
src_key_padding_mask
|
296 |
-
):
|
297 |
-
raise AssertionError(
|
298 |
-
"only bool and floating types of key_padding_mask are supported"
|
299 |
-
)
|
300 |
-
|
301 |
-
if self.norm_first:
|
302 |
-
x = x + self._sa_block(
|
303 |
-
self.norm1(x, stage_embedding),
|
304 |
-
src_mask,
|
305 |
-
src_key_padding_mask,
|
306 |
-
cache=cache,
|
307 |
-
)
|
308 |
-
x = x + self._ff_block(self.norm2(x, stage_embedding))
|
309 |
-
else:
|
310 |
-
x = self.norm1(
|
311 |
-
x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
|
312 |
-
stage_embedding,
|
313 |
-
)
|
314 |
-
x = self.norm2(x + self._ff_block(x), stage_embedding)
|
315 |
-
|
316 |
-
if is_src_tuple:
|
317 |
-
return (x, stage_embedding)
|
318 |
-
return x
|
319 |
-
|
320 |
-
# self-attention block
|
321 |
-
def _sa_block(
|
322 |
-
self,
|
323 |
-
x: Tensor,
|
324 |
-
attn_mask: Optional[Tensor],
|
325 |
-
key_padding_mask: Optional[Tensor],
|
326 |
-
cache=None,
|
327 |
-
) -> Tensor:
|
328 |
-
# print(x.shape,attn_mask.shape,key_padding_mask)
|
329 |
-
# torch.Size([1, 188, 512]) torch.Size([188, 188]) None
|
330 |
-
# import os
|
331 |
-
# os._exit(23333)
|
332 |
-
x = self.self_attn(
|
333 |
-
x,
|
334 |
-
x,
|
335 |
-
x,
|
336 |
-
attn_mask=attn_mask,
|
337 |
-
key_padding_mask=key_padding_mask,
|
338 |
-
need_weights=False,
|
339 |
-
cache=cache,
|
340 |
-
)[0]
|
341 |
-
return self.dropout1(x)
|
342 |
-
|
343 |
-
# feed forward block
|
344 |
-
def _ff_block(self, x: Tensor) -> Tensor:
|
345 |
-
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
346 |
-
return self.dropout2(x)
|
347 |
-
|
348 |
-
|
349 |
-
class AdaptiveLayerNorm(nn.Module):
|
350 |
-
r"""Adaptive Layer Normalization"""
|
351 |
-
|
352 |
-
def __init__(self, d_model, norm) -> None:
|
353 |
-
super(AdaptiveLayerNorm, self).__init__()
|
354 |
-
self.project_layer = nn.Linear(d_model, 2 * d_model)
|
355 |
-
self.norm = norm
|
356 |
-
self.d_model = d_model
|
357 |
-
self.eps = self.norm.eps
|
358 |
-
|
359 |
-
def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
|
360 |
-
if isinstance(input, tuple):
|
361 |
-
input, embedding = input
|
362 |
-
weight, bias = torch.split(
|
363 |
-
self.project_layer(embedding),
|
364 |
-
split_size_or_sections=self.d_model,
|
365 |
-
dim=-1,
|
366 |
-
)
|
367 |
-
return (weight * self.norm(input) + bias, embedding)
|
368 |
-
|
369 |
-
weight, bias = torch.split(
|
370 |
-
self.project_layer(embedding),
|
371 |
-
split_size_or_sections=self.d_model,
|
372 |
-
dim=-1,
|
373 |
-
)
|
374 |
-
return weight * self.norm(input) + bias
|
375 |
-
|
376 |
-
|
377 |
-
def _get_clones(module, N):
|
378 |
-
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/modules/transformer_onnx.py
DELETED
@@ -1,292 +0,0 @@
|
|
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(
|
46 |
-
torch.empty(self.normalized_shape, **factory_kwargs)
|
47 |
-
)
|
48 |
-
self.bias = nn.Parameter(
|
49 |
-
torch.empty(self.normalized_shape, **factory_kwargs)
|
50 |
-
)
|
51 |
-
else:
|
52 |
-
self.register_parameter("weight", None)
|
53 |
-
self.register_parameter("bias", None)
|
54 |
-
|
55 |
-
self.reset_parameters()
|
56 |
-
|
57 |
-
def reset_parameters(self) -> None:
|
58 |
-
if self.elementwise_affine:
|
59 |
-
nn.init.ones_(self.weight)
|
60 |
-
nn.init.zeros_(self.bias)
|
61 |
-
|
62 |
-
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
63 |
-
if isinstance(input, tuple):
|
64 |
-
input, embedding = input
|
65 |
-
return (
|
66 |
-
F.layer_norm(
|
67 |
-
input,
|
68 |
-
self.normalized_shape,
|
69 |
-
self.weight,
|
70 |
-
self.bias,
|
71 |
-
self.eps,
|
72 |
-
),
|
73 |
-
embedding,
|
74 |
-
)
|
75 |
-
|
76 |
-
assert embedding is None
|
77 |
-
return F.layer_norm(
|
78 |
-
input, self.normalized_shape, self.weight, self.bias, self.eps
|
79 |
-
)
|
80 |
-
|
81 |
-
def extra_repr(self) -> str:
|
82 |
-
return (
|
83 |
-
"{normalized_shape}, eps={eps}, "
|
84 |
-
"elementwise_affine={elementwise_affine}".format(**self.__dict__)
|
85 |
-
)
|
86 |
-
|
87 |
-
|
88 |
-
class IdentityNorm(nn.Module):
|
89 |
-
def __init__(
|
90 |
-
self,
|
91 |
-
d_model: int,
|
92 |
-
eps: float = 1e-5,
|
93 |
-
device=None,
|
94 |
-
dtype=None,
|
95 |
-
) -> None:
|
96 |
-
super(IdentityNorm, self).__init__()
|
97 |
-
|
98 |
-
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
99 |
-
if isinstance(input, tuple):
|
100 |
-
return input
|
101 |
-
|
102 |
-
assert embedding is None
|
103 |
-
return input
|
104 |
-
|
105 |
-
|
106 |
-
class TransformerEncoder(nn.Module):
|
107 |
-
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
|
108 |
-
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
|
109 |
-
|
110 |
-
Args:
|
111 |
-
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
|
112 |
-
num_layers: the number of sub-encoder-layers in the encoder (required).
|
113 |
-
norm: the layer normalization component (optional).
|
114 |
-
enable_nested_tensor: if True, input will automatically convert to nested tensor
|
115 |
-
(and convert back on output). This will improve the overall performance of
|
116 |
-
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
|
117 |
-
|
118 |
-
Examples::
|
119 |
-
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
|
120 |
-
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
|
121 |
-
>>> src = torch.rand(10, 32, 512)
|
122 |
-
>>> out = transformer_encoder(src)
|
123 |
-
"""
|
124 |
-
__constants__ = ["norm"]
|
125 |
-
|
126 |
-
def __init__(self, encoder_layer, num_layers, norm=None):
|
127 |
-
super(TransformerEncoder, self).__init__()
|
128 |
-
self.layers = _get_clones(encoder_layer, num_layers)
|
129 |
-
self.num_layers = num_layers
|
130 |
-
self.norm = norm
|
131 |
-
|
132 |
-
def forward(
|
133 |
-
self,
|
134 |
-
src: Tensor,
|
135 |
-
mask: Optional[Tensor] = None,
|
136 |
-
src_key_padding_mask: Optional[Tensor] = None,
|
137 |
-
return_layer_states: bool = False,
|
138 |
-
cache=None,
|
139 |
-
) -> Tensor:
|
140 |
-
output = src
|
141 |
-
for mod in self.layers:
|
142 |
-
output = mod(
|
143 |
-
output,
|
144 |
-
src_mask=mask,
|
145 |
-
src_key_padding_mask=src_key_padding_mask,
|
146 |
-
cache=cache,
|
147 |
-
)
|
148 |
-
|
149 |
-
if self.norm is not None:
|
150 |
-
output = self.norm(output)
|
151 |
-
|
152 |
-
return output
|
153 |
-
|
154 |
-
|
155 |
-
class TransformerEncoderLayer(nn.Module):
|
156 |
-
__constants__ = ["batch_first", "norm_first"]
|
157 |
-
def __init__(
|
158 |
-
self,
|
159 |
-
d_model: int,
|
160 |
-
nhead: int,
|
161 |
-
dim_feedforward: int = 2048,
|
162 |
-
dropout: float = 0.1,
|
163 |
-
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
164 |
-
batch_first: bool = False,
|
165 |
-
norm_first: bool = False,
|
166 |
-
device=None,
|
167 |
-
dtype=None,
|
168 |
-
linear1_self_attention_cls: nn.Module = nn.Linear,
|
169 |
-
linear2_self_attention_cls: nn.Module = nn.Linear,
|
170 |
-
linear1_feedforward_cls: nn.Module = nn.Linear,
|
171 |
-
linear2_feedforward_cls: nn.Module = nn.Linear,
|
172 |
-
layer_norm_cls: nn.Module = LayerNorm,
|
173 |
-
layer_norm_eps: float = 1e-5,
|
174 |
-
adaptive_layer_norm=False,
|
175 |
-
) -> None:
|
176 |
-
factory_kwargs = {"device": device, "dtype": dtype}
|
177 |
-
super(TransformerEncoderLayer, self).__init__()
|
178 |
-
self.self_attn = MultiheadAttention(
|
179 |
-
d_model, # 512 16
|
180 |
-
nhead,
|
181 |
-
dropout=dropout,
|
182 |
-
batch_first=batch_first,
|
183 |
-
linear1_cls=linear1_self_attention_cls,
|
184 |
-
linear2_cls=linear2_self_attention_cls,
|
185 |
-
**factory_kwargs,
|
186 |
-
)
|
187 |
-
self.linear1 = linear1_feedforward_cls(
|
188 |
-
d_model, dim_feedforward, **factory_kwargs
|
189 |
-
)
|
190 |
-
self.dropout = nn.Dropout(dropout)
|
191 |
-
self.linear2 = linear2_feedforward_cls(
|
192 |
-
dim_feedforward, d_model, **factory_kwargs
|
193 |
-
)
|
194 |
-
self.norm_first = norm_first
|
195 |
-
self.dropout1 = nn.Dropout(dropout)
|
196 |
-
self.dropout2 = nn.Dropout(dropout)
|
197 |
-
if isinstance(activation, str):
|
198 |
-
activation = _get_activation_fn(activation)
|
199 |
-
elif isinstance(activation, partial):
|
200 |
-
activation = activation(d_model)
|
201 |
-
elif activation == BalancedDoubleSwish:
|
202 |
-
activation = BalancedDoubleSwish(d_model)
|
203 |
-
self.activation = activation
|
204 |
-
|
205 |
-
norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
206 |
-
if layer_norm_cls == IdentityNorm:
|
207 |
-
norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
208 |
-
else:
|
209 |
-
norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
210 |
-
|
211 |
-
if adaptive_layer_norm:
|
212 |
-
self.norm1 = AdaptiveLayerNorm(d_model, norm1)
|
213 |
-
self.norm2 = AdaptiveLayerNorm(d_model, norm2)
|
214 |
-
else:
|
215 |
-
self.norm1 = norm1
|
216 |
-
self.norm2 = norm2
|
217 |
-
|
218 |
-
def __setstate__(self, state):
|
219 |
-
super(TransformerEncoderLayer, self).__setstate__(state)
|
220 |
-
if not hasattr(self, "activation"):
|
221 |
-
self.activation = F.relu
|
222 |
-
|
223 |
-
def forward(
|
224 |
-
self,
|
225 |
-
src: Tensor,
|
226 |
-
src_mask: Optional[Tensor] = None,
|
227 |
-
src_key_padding_mask: Optional[Tensor] = None,
|
228 |
-
cache=None,
|
229 |
-
) -> Tensor:
|
230 |
-
x = src
|
231 |
-
stage_embedding = None
|
232 |
-
x = self.norm1(
|
233 |
-
x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
|
234 |
-
stage_embedding,
|
235 |
-
)
|
236 |
-
x = self.norm2(x + self._ff_block(x), stage_embedding)
|
237 |
-
|
238 |
-
return x
|
239 |
-
|
240 |
-
def _sa_block(
|
241 |
-
self,
|
242 |
-
x: Tensor,
|
243 |
-
attn_mask: Optional[Tensor],
|
244 |
-
key_padding_mask: Optional[Tensor],
|
245 |
-
cache=None,
|
246 |
-
) -> Tensor:
|
247 |
-
x = self.self_attn(
|
248 |
-
x,
|
249 |
-
x,
|
250 |
-
x,
|
251 |
-
attn_mask=attn_mask,
|
252 |
-
key_padding_mask=key_padding_mask,
|
253 |
-
need_weights=False,
|
254 |
-
cache=cache,
|
255 |
-
)
|
256 |
-
return self.dropout1(x)
|
257 |
-
|
258 |
-
def _ff_block(self, x: Tensor) -> Tensor:
|
259 |
-
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
260 |
-
return self.dropout2(x)
|
261 |
-
|
262 |
-
|
263 |
-
class AdaptiveLayerNorm(nn.Module):
|
264 |
-
r"""Adaptive Layer Normalization"""
|
265 |
-
|
266 |
-
def __init__(self, d_model, norm) -> None:
|
267 |
-
super(AdaptiveLayerNorm, self).__init__()
|
268 |
-
self.project_layer = nn.Linear(d_model, 2 * d_model)
|
269 |
-
self.norm = norm
|
270 |
-
self.d_model = d_model
|
271 |
-
self.eps = self.norm.eps
|
272 |
-
|
273 |
-
def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
|
274 |
-
if isinstance(input, tuple):
|
275 |
-
input, embedding = input
|
276 |
-
weight, bias = torch.split(
|
277 |
-
self.project_layer(embedding),
|
278 |
-
split_size_or_sections=self.d_model,
|
279 |
-
dim=-1,
|
280 |
-
)
|
281 |
-
return (weight * self.norm(input) + bias, embedding)
|
282 |
-
|
283 |
-
weight, bias = torch.split(
|
284 |
-
self.project_layer(embedding),
|
285 |
-
split_size_or_sections=self.d_model,
|
286 |
-
dim=-1,
|
287 |
-
)
|
288 |
-
return weight * self.norm(input) + bias
|
289 |
-
|
290 |
-
|
291 |
-
def _get_clones(module, N):
|
292 |
-
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/text_processing/__init__.py
DELETED
File without changes
|
AR/text_processing/phonemizer.py
DELETED
@@ -1,79 +0,0 @@
|
|
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 = (
|
34 |
-
rf"([{''.join(self._special_cases_dict.keys())}])"
|
35 |
-
)
|
36 |
-
|
37 |
-
def _normalize_punctuation(self, text: str) -> str:
|
38 |
-
text = regex.sub(rf"\pZ+{self._punctuation_regexp}", r"\1", text)
|
39 |
-
text = regex.sub(rf"{self._punctuation_regexp}(\pL)", r"\1 \2", text)
|
40 |
-
text = regex.sub(r"\pZ+", r" ", text)
|
41 |
-
return text.strip()
|
42 |
-
|
43 |
-
def _convert_punctuation(self, word: Word) -> str:
|
44 |
-
if not word.phonemes:
|
45 |
-
return ""
|
46 |
-
if word.phonemes[0] in ["‖", "|"]:
|
47 |
-
return word.text.strip()
|
48 |
-
|
49 |
-
phonemes = "".join(word.phonemes)
|
50 |
-
# remove modifier characters ˈˌː with regex
|
51 |
-
phonemes = re.sub(r"[ˈˌː͡]", "", phonemes)
|
52 |
-
return phonemes.strip()
|
53 |
-
|
54 |
-
def phonemize(self, text: str, espeak: bool = False) -> str:
|
55 |
-
text_to_phonemize: str = self._normalize_punctuation(text)
|
56 |
-
sents: List[Sentence] = [
|
57 |
-
sent
|
58 |
-
for sent in self._phonemizer(text_to_phonemize, lang="en-us", espeak=espeak)
|
59 |
-
]
|
60 |
-
words: List[str] = [
|
61 |
-
self._convert_punctuation(word) for word in itertools.chain(*sents)
|
62 |
-
]
|
63 |
-
return " ".join(words)
|
64 |
-
|
65 |
-
def transform(self, phonemes):
|
66 |
-
# convert phonemes to ids
|
67 |
-
# dictionary is in symbols.py
|
68 |
-
return [self.symbol_to_id[p] for p in phonemes if p in self.symbol_to_id.keys()]
|
69 |
-
|
70 |
-
|
71 |
-
if __name__ == "__main__":
|
72 |
-
phonemizer = GruutPhonemizer("en-us")
|
73 |
-
# text -> IPA
|
74 |
-
phonemes = phonemizer.phonemize("Hello, wor-ld ?")
|
75 |
-
print("phonemes:", phonemes)
|
76 |
-
print("len(phonemes):", len(phonemes))
|
77 |
-
phoneme_ids = phonemizer.transform(phonemes)
|
78 |
-
print("phoneme_ids:", phoneme_ids)
|
79 |
-
print("len(phoneme_ids):", len(phoneme_ids))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/text_processing/symbols.py
DELETED
@@ -1,10 +0,0 @@
|
|
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 |
-
SYMBOLS = [PAD] + list(PUNCTUATION) + list(LETTERS) + list(IPA_LETTERS)
|
8 |
-
SPACE_ID = SYMBOLS.index(" ")
|
9 |
-
SYMBOL_TO_ID = {s: i for i, s in enumerate(SYMBOLS)}
|
10 |
-
ID_TO_SYMBOL = {i: s for i, s in enumerate(SYMBOLS)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/utils/__init__.py
DELETED
@@ -1,37 +0,0 @@
|
|
1 |
-
import re
|
2 |
-
|
3 |
-
|
4 |
-
def str2bool(str):
|
5 |
-
return True if str.lower() == 'true' else False
|
6 |
-
|
7 |
-
|
8 |
-
def get_newest_ckpt(string_list):
|
9 |
-
# 定义一个正则表达式模式,用于匹配字符串中的数字
|
10 |
-
pattern = r'epoch=(\d+)-step=(\d+)\.ckpt'
|
11 |
-
|
12 |
-
# 使用正则表达式提取每个字符串中的数字信息,并创建一个包含元组的列表
|
13 |
-
extracted_info = []
|
14 |
-
for string in string_list:
|
15 |
-
match = re.match(pattern, string)
|
16 |
-
if match:
|
17 |
-
epoch = int(match.group(1))
|
18 |
-
step = int(match.group(2))
|
19 |
-
extracted_info.append((epoch, step, string))
|
20 |
-
# 按照 epoch 后面的数字和 step 后面的数字进行排序
|
21 |
-
sorted_info = sorted(
|
22 |
-
extracted_info, key=lambda x: (x[0], x[1]), reverse=True)
|
23 |
-
# 获取最新的 ckpt 文件名
|
24 |
-
newest_ckpt = sorted_info[0][2]
|
25 |
-
return newest_ckpt
|
26 |
-
|
27 |
-
|
28 |
-
# 文本存在且不为空时 return True
|
29 |
-
def check_txt_file(file_path):
|
30 |
-
try:
|
31 |
-
with open(file_path, 'r') as file:
|
32 |
-
text = file.readline().strip()
|
33 |
-
assert text.strip() != ''
|
34 |
-
return text
|
35 |
-
except Exception:
|
36 |
-
return False
|
37 |
-
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/utils/initialize.py
DELETED
@@ -1,38 +0,0 @@
|
|
1 |
-
#!/usr/bin/env python3
|
2 |
-
"""Initialize modules for espnet2 neural networks."""
|
3 |
-
import torch
|
4 |
-
from typeguard import check_argument_types
|
5 |
-
|
6 |
-
|
7 |
-
def initialize(model: torch.nn.Module, init: str):
|
8 |
-
"""Initialize weights of a neural network module.
|
9 |
-
|
10 |
-
Parameters are initialized using the given method or distribution.
|
11 |
-
|
12 |
-
Custom initialization routines can be implemented into submodules
|
13 |
-
as function `espnet_initialization_fn` within the custom module.
|
14 |
-
|
15 |
-
Args:
|
16 |
-
model: Target.
|
17 |
-
init: Method of initialization.
|
18 |
-
"""
|
19 |
-
assert check_argument_types()
|
20 |
-
print("init with", init)
|
21 |
-
|
22 |
-
# weight init
|
23 |
-
for p in model.parameters():
|
24 |
-
if p.dim() > 1:
|
25 |
-
if init == "xavier_uniform":
|
26 |
-
torch.nn.init.xavier_uniform_(p.data)
|
27 |
-
elif init == "xavier_normal":
|
28 |
-
torch.nn.init.xavier_normal_(p.data)
|
29 |
-
elif init == "kaiming_uniform":
|
30 |
-
torch.nn.init.kaiming_uniform_(p.data, nonlinearity="relu")
|
31 |
-
elif init == "kaiming_normal":
|
32 |
-
torch.nn.init.kaiming_normal_(p.data, nonlinearity="relu")
|
33 |
-
else:
|
34 |
-
raise ValueError("Unknown initialization: " + init)
|
35 |
-
# bias init
|
36 |
-
for name, p in model.named_parameters():
|
37 |
-
if ".bias" in name and p.dim() == 1:
|
38 |
-
p.data.zero_()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AR/utils/io.py
DELETED
@@ -1,34 +0,0 @@
|
|
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(
|
22 |
-
(name, getattr(args, name)) for name in dir(args) if not name.startswith("_")
|
23 |
-
)
|
24 |
-
with open(path, "a") as args_file:
|
25 |
-
args_file.write("==> torch version: {}\n".format(torch.__version__))
|
26 |
-
args_file.write(
|
27 |
-
"==> cudnn version: {}\n".format(torch.backends.cudnn.version())
|
28 |
-
)
|
29 |
-
args_file.write("==> Cmd:\n")
|
30 |
-
args_file.write(str(sys.argv))
|
31 |
-
args_file.write("\n==> args:\n")
|
32 |
-
for k, v in sorted(args_dict.items()):
|
33 |
-
args_file.write(" %s: %s\n" % (str(k), str(v)))
|
34 |
-
args_file.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
inference_cli.py
DELETED
@@ -1,55 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
import os
|
3 |
-
import soundfile as sf
|
4 |
-
|
5 |
-
from tools.i18n.i18n import I18nAuto
|
6 |
-
from GPT_SoVITS.inference_webui import change_gpt_weights, change_sovits_weights, get_tts_wav
|
7 |
-
|
8 |
-
i18n = I18nAuto()
|
9 |
-
|
10 |
-
def synthesize(GPT_model_path, SoVITS_model_path, ref_audio_path, ref_text_path, ref_language, target_text_path, target_language, output_path):
|
11 |
-
# Read reference text
|
12 |
-
with open(ref_text_path, 'r', encoding='utf-8') as file:
|
13 |
-
ref_text = file.read()
|
14 |
-
|
15 |
-
# Read target text
|
16 |
-
with open(target_text_path, 'r', encoding='utf-8') as file:
|
17 |
-
target_text = file.read()
|
18 |
-
|
19 |
-
# Change model weights
|
20 |
-
change_gpt_weights(gpt_path=GPT_model_path)
|
21 |
-
change_sovits_weights(sovits_path=SoVITS_model_path)
|
22 |
-
|
23 |
-
# Synthesize audio
|
24 |
-
synthesis_result = get_tts_wav(ref_wav_path=ref_audio_path,
|
25 |
-
prompt_text=ref_text,
|
26 |
-
prompt_language=i18n(ref_language),
|
27 |
-
text=target_text,
|
28 |
-
text_language=i18n(target_language), top_p=1, temperature=1)
|
29 |
-
|
30 |
-
result_list = list(synthesis_result)
|
31 |
-
|
32 |
-
if result_list:
|
33 |
-
last_sampling_rate, last_audio_data = result_list[-1]
|
34 |
-
output_wav_path = os.path.join(output_path, "output.wav")
|
35 |
-
sf.write(output_wav_path, last_audio_data, last_sampling_rate)
|
36 |
-
print(f"Audio saved to {output_wav_path}")
|
37 |
-
|
38 |
-
def main():
|
39 |
-
parser = argparse.ArgumentParser(description="GPT-SoVITS Command Line Tool")
|
40 |
-
parser.add_argument('--gpt_model', required=True, help="Path to the GPT model file")
|
41 |
-
parser.add_argument('--sovits_model', required=True, help="Path to the SoVITS model file")
|
42 |
-
parser.add_argument('--ref_audio', required=True, help="Path to the reference audio file")
|
43 |
-
parser.add_argument('--ref_text', required=True, help="Path to the reference text file")
|
44 |
-
parser.add_argument('--ref_language', required=True, choices=["中文", "英文", "日文"], help="Language of the reference audio")
|
45 |
-
parser.add_argument('--target_text', required=True, help="Path to the target text file")
|
46 |
-
parser.add_argument('--target_language', required=True, choices=["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"], help="Language of the target text")
|
47 |
-
parser.add_argument('--output_path', required=True, help="Path to the output directory")
|
48 |
-
|
49 |
-
args = parser.parse_args()
|
50 |
-
|
51 |
-
synthesize(args.gpt_model, args.sovits_model, args.ref_audio, args.ref_text, args.ref_language, args.target_text, args.target_language, args.output_path)
|
52 |
-
|
53 |
-
if __name__ == '__main__':
|
54 |
-
main()
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
inference_gui.py
DELETED
@@ -1,310 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import sys
|
3 |
-
from PyQt5.QtCore import QEvent
|
4 |
-
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QTextEdit
|
5 |
-
from PyQt5.QtWidgets import QGridLayout, QVBoxLayout, QWidget, QFileDialog, QStatusBar, QComboBox
|
6 |
-
import soundfile as sf
|
7 |
-
|
8 |
-
from tools.i18n.i18n import I18nAuto
|
9 |
-
i18n = I18nAuto()
|
10 |
-
|
11 |
-
from inference_webui import gpt_path, sovits_path, change_gpt_weights, change_sovits_weights, get_tts_wav
|
12 |
-
|
13 |
-
|
14 |
-
class GPTSoVITSGUI(QMainWindow):
|
15 |
-
GPT_Path = gpt_path
|
16 |
-
SoVITS_Path = sovits_path
|
17 |
-
|
18 |
-
def __init__(self):
|
19 |
-
super().__init__()
|
20 |
-
|
21 |
-
self.setWindowTitle('GPT-SoVITS GUI')
|
22 |
-
self.setGeometry(800, 450, 950, 850)
|
23 |
-
|
24 |
-
self.setStyleSheet("""
|
25 |
-
QWidget {
|
26 |
-
background-color: #a3d3b1;
|
27 |
-
}
|
28 |
-
|
29 |
-
QTabWidget::pane {
|
30 |
-
background-color: #a3d3b1;
|
31 |
-
}
|
32 |
-
|
33 |
-
QTabWidget::tab-bar {
|
34 |
-
alignment: left;
|
35 |
-
}
|
36 |
-
|
37 |
-
QTabBar::tab {
|
38 |
-
background: #8da4bf;
|
39 |
-
color: #ffffff;
|
40 |
-
padding: 8px;
|
41 |
-
}
|
42 |
-
|
43 |
-
QTabBar::tab:selected {
|
44 |
-
background: #2a3f54;
|
45 |
-
}
|
46 |
-
|
47 |
-
QLabel {
|
48 |
-
color: #000000;
|
49 |
-
}
|
50 |
-
|
51 |
-
QPushButton {
|
52 |
-
background-color: #4CAF50;
|
53 |
-
color: white;
|
54 |
-
padding: 8px;
|
55 |
-
border: 1px solid #4CAF50;
|
56 |
-
border-radius: 4px;
|
57 |
-
}
|
58 |
-
|
59 |
-
QPushButton:hover {
|
60 |
-
background-color: #45a049;
|
61 |
-
border: 1px solid #45a049;
|
62 |
-
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
|
63 |
-
}
|
64 |
-
""")
|
65 |
-
|
66 |
-
license_text = (
|
67 |
-
"本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责. "
|
68 |
-
"如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录LICENSE.")
|
69 |
-
license_label = QLabel(license_text)
|
70 |
-
license_label.setWordWrap(True)
|
71 |
-
|
72 |
-
self.GPT_model_label = QLabel("选择GPT模型:")
|
73 |
-
self.GPT_model_input = QLineEdit()
|
74 |
-
self.GPT_model_input.setPlaceholderText("拖拽或选择文件")
|
75 |
-
self.GPT_model_input.setText(self.GPT_Path)
|
76 |
-
self.GPT_model_input.setReadOnly(True)
|
77 |
-
self.GPT_model_button = QPushButton("选择GPT模型文件")
|
78 |
-
self.GPT_model_button.clicked.connect(self.select_GPT_model)
|
79 |
-
|
80 |
-
self.SoVITS_model_label = QLabel("选择SoVITS模型:")
|
81 |
-
self.SoVITS_model_input = QLineEdit()
|
82 |
-
self.SoVITS_model_input.setPlaceholderText("拖拽或选择文件")
|
83 |
-
self.SoVITS_model_input.setText(self.SoVITS_Path)
|
84 |
-
self.SoVITS_model_input.setReadOnly(True)
|
85 |
-
self.SoVITS_model_button = QPushButton("选择SoVITS模型文件")
|
86 |
-
self.SoVITS_model_button.clicked.connect(self.select_SoVITS_model)
|
87 |
-
|
88 |
-
self.ref_audio_label = QLabel("上传参考音频:")
|
89 |
-
self.ref_audio_input = QLineEdit()
|
90 |
-
self.ref_audio_input.setPlaceholderText("拖拽或选择文件")
|
91 |
-
self.ref_audio_input.setReadOnly(True)
|
92 |
-
self.ref_audio_button = QPushButton("选择音频文件")
|
93 |
-
self.ref_audio_button.clicked.connect(self.select_ref_audio)
|
94 |
-
|
95 |
-
self.ref_text_label = QLabel("参考音频文本:")
|
96 |
-
self.ref_text_input = QLineEdit()
|
97 |
-
self.ref_text_input.setPlaceholderText("直接输入文字或上传文本")
|
98 |
-
self.ref_text_button = QPushButton("上传文本")
|
99 |
-
self.ref_text_button.clicked.connect(self.upload_ref_text)
|
100 |
-
|
101 |
-
self.ref_language_label = QLabel("参考音频语言:")
|
102 |
-
self.ref_language_combobox = QComboBox()
|
103 |
-
self.ref_language_combobox.addItems(["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"])
|
104 |
-
self.ref_language_combobox.setCurrentText("多语种混合")
|
105 |
-
|
106 |
-
self.target_text_label = QLabel("合成目标文本:")
|
107 |
-
self.target_text_input = QLineEdit()
|
108 |
-
self.target_text_input.setPlaceholderText("直接输入文字或上传文本")
|
109 |
-
self.target_text_button = QPushButton("上传文本")
|
110 |
-
self.target_text_button.clicked.connect(self.upload_target_text)
|
111 |
-
|
112 |
-
self.target_language_label = QLabel("合成音频语言:")
|
113 |
-
self.target_language_combobox = QComboBox()
|
114 |
-
self.target_language_combobox.addItems(["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"])
|
115 |
-
self.target_language_combobox.setCurrentText("多语种混合")
|
116 |
-
|
117 |
-
self.output_label = QLabel("输出音频路径:")
|
118 |
-
self.output_input = QLineEdit()
|
119 |
-
self.output_input.setPlaceholderText("拖拽或选择文件")
|
120 |
-
self.output_input.setReadOnly(True)
|
121 |
-
self.output_button = QPushButton("选择文件夹")
|
122 |
-
self.output_button.clicked.connect(self.select_output_path)
|
123 |
-
|
124 |
-
self.output_text = QTextEdit()
|
125 |
-
self.output_text.setReadOnly(True)
|
126 |
-
|
127 |
-
self.add_drag_drop_events([
|
128 |
-
self.GPT_model_input,
|
129 |
-
self.SoVITS_model_input,
|
130 |
-
self.ref_audio_input,
|
131 |
-
self.ref_text_input,
|
132 |
-
self.target_text_input,
|
133 |
-
self.output_input,
|
134 |
-
])
|
135 |
-
|
136 |
-
self.synthesize_button = QPushButton("合成")
|
137 |
-
self.synthesize_button.clicked.connect(self.synthesize)
|
138 |
-
|
139 |
-
self.clear_output_button = QPushButton("清空输出")
|
140 |
-
self.clear_output_button.clicked.connect(self.clear_output)
|
141 |
-
|
142 |
-
self.status_bar = QStatusBar()
|
143 |
-
|
144 |
-
main_layout = QVBoxLayout()
|
145 |
-
|
146 |
-
input_layout = QGridLayout(self)
|
147 |
-
input_layout.setSpacing(10)
|
148 |
-
|
149 |
-
input_layout.addWidget(license_label, 0, 0, 1, 3)
|
150 |
-
|
151 |
-
input_layout.addWidget(self.GPT_model_label, 1, 0)
|
152 |
-
input_layout.addWidget(self.GPT_model_input, 2, 0, 1, 2)
|
153 |
-
input_layout.addWidget(self.GPT_model_button, 2, 2)
|
154 |
-
|
155 |
-
input_layout.addWidget(self.SoVITS_model_label, 3, 0)
|
156 |
-
input_layout.addWidget(self.SoVITS_model_input, 4, 0, 1, 2)
|
157 |
-
input_layout.addWidget(self.SoVITS_model_button, 4, 2)
|
158 |
-
|
159 |
-
input_layout.addWidget(self.ref_audio_label, 5, 0)
|
160 |
-
input_layout.addWidget(self.ref_audio_input, 6, 0, 1, 2)
|
161 |
-
input_layout.addWidget(self.ref_audio_button, 6, 2)
|
162 |
-
|
163 |
-
input_layout.addWidget(self.ref_language_label, 7, 0)
|
164 |
-
input_layout.addWidget(self.ref_language_combobox, 8, 0, 1, 1)
|
165 |
-
input_layout.addWidget(self.ref_text_label, 9, 0)
|
166 |
-
input_layout.addWidget(self.ref_text_input, 10, 0, 1, 2)
|
167 |
-
input_layout.addWidget(self.ref_text_button, 10, 2)
|
168 |
-
|
169 |
-
input_layout.addWidget(self.target_language_label, 11, 0)
|
170 |
-
input_layout.addWidget(self.target_language_combobox, 12, 0, 1, 1)
|
171 |
-
input_layout.addWidget(self.target_text_label, 13, 0)
|
172 |
-
input_layout.addWidget(self.target_text_input, 14, 0, 1, 2)
|
173 |
-
input_layout.addWidget(self.target_text_button, 14, 2)
|
174 |
-
|
175 |
-
input_layout.addWidget(self.output_label, 15, 0)
|
176 |
-
input_layout.addWidget(self.output_input, 16, 0, 1, 2)
|
177 |
-
input_layout.addWidget(self.output_button, 16, 2)
|
178 |
-
|
179 |
-
main_layout.addLayout(input_layout)
|
180 |
-
|
181 |
-
output_layout = QVBoxLayout()
|
182 |
-
output_layout.addWidget(self.output_text)
|
183 |
-
main_layout.addLayout(output_layout)
|
184 |
-
|
185 |
-
main_layout.addWidget(self.synthesize_button)
|
186 |
-
|
187 |
-
main_layout.addWidget(self.clear_output_button)
|
188 |
-
|
189 |
-
main_layout.addWidget(self.status_bar)
|
190 |
-
|
191 |
-
self.central_widget = QWidget()
|
192 |
-
self.central_widget.setLayout(main_layout)
|
193 |
-
self.setCentralWidget(self.central_widget)
|
194 |
-
|
195 |
-
def dragEnterEvent(self, event):
|
196 |
-
if event.mimeData().hasUrls():
|
197 |
-
event.acceptProposedAction()
|
198 |
-
|
199 |
-
def dropEvent(self, event):
|
200 |
-
if event.mimeData().hasUrls():
|
201 |
-
file_paths = [url.toLocalFile() for url in event.mimeData().urls()]
|
202 |
-
if len(file_paths) == 1:
|
203 |
-
self.update_ref_audio(file_paths[0])
|
204 |
-
else:
|
205 |
-
self.update_ref_audio(", ".join(file_paths))
|
206 |
-
|
207 |
-
def add_drag_drop_events(self, widgets):
|
208 |
-
for widget in widgets:
|
209 |
-
widget.setAcceptDrops(True)
|
210 |
-
widget.installEventFilter(self)
|
211 |
-
|
212 |
-
def eventFilter(self, obj, event):
|
213 |
-
if event.type() in (QEvent.DragEnter, QEvent.Drop):
|
214 |
-
mime_data = event.mimeData()
|
215 |
-
if mime_data.hasUrls():
|
216 |
-
event.acceptProposedAction()
|
217 |
-
|
218 |
-
return super().eventFilter(obj, event)
|
219 |
-
|
220 |
-
def select_GPT_model(self):
|
221 |
-
file_path, _ = QFileDialog.getOpenFileName(self, "选择GPT模型文件", "", "GPT Files (*.ckpt)")
|
222 |
-
if file_path:
|
223 |
-
self.GPT_model_input.setText(file_path)
|
224 |
-
|
225 |
-
def select_SoVITS_model(self):
|
226 |
-
file_path, _ = QFileDialog.getOpenFileName(self, "选择SoVITS模型文件", "", "SoVITS Files (*.pth)")
|
227 |
-
if file_path:
|
228 |
-
self.SoVITS_model_input.setText(file_path)
|
229 |
-
|
230 |
-
def select_ref_audio(self):
|
231 |
-
file_path, _ = QFileDialog.getOpenFileName(self, "选择参考音频文件", "", "Audio Files (*.wav *.mp3)")
|
232 |
-
if file_path:
|
233 |
-
self.update_ref_audio(file_path)
|
234 |
-
|
235 |
-
def upload_ref_text(self):
|
236 |
-
file_path, _ = QFileDialog.getOpenFileName(self, "选择文本文件", "", "Text Files (*.txt)")
|
237 |
-
if file_path:
|
238 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
239 |
-
content = file.read()
|
240 |
-
self.ref_text_input.setText(content)
|
241 |
-
|
242 |
-
def upload_target_text(self):
|
243 |
-
file_path, _ = QFileDialog.getOpenFileName(self, "选择文本文件", "", "Text Files (*.txt)")
|
244 |
-
if file_path:
|
245 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
246 |
-
content = file.read()
|
247 |
-
self.target_text_input.setText(content)
|
248 |
-
|
249 |
-
def select_output_path(self):
|
250 |
-
options = QFileDialog.Options()
|
251 |
-
options |= QFileDialog.DontUseNativeDialog
|
252 |
-
options |= QFileDialog.ShowDirsOnly
|
253 |
-
|
254 |
-
folder_dialog = QFileDialog()
|
255 |
-
folder_dialog.setOptions(options)
|
256 |
-
folder_dialog.setFileMode(QFileDialog.Directory)
|
257 |
-
|
258 |
-
if folder_dialog.exec_():
|
259 |
-
folder_path = folder_dialog.selectedFiles()[0]
|
260 |
-
self.output_input.setText(folder_path)
|
261 |
-
|
262 |
-
def update_ref_audio(self, file_path):
|
263 |
-
self.ref_audio_input.setText(file_path)
|
264 |
-
|
265 |
-
def clear_output(self):
|
266 |
-
self.output_text.clear()
|
267 |
-
|
268 |
-
def synthesize(self):
|
269 |
-
GPT_model_path = self.GPT_model_input.text()
|
270 |
-
SoVITS_model_path = self.SoVITS_model_input.text()
|
271 |
-
ref_audio_path = self.ref_audio_input.text()
|
272 |
-
language_combobox = self.ref_language_combobox.currentText()
|
273 |
-
language_combobox = i18n(language_combobox)
|
274 |
-
ref_text = self.ref_text_input.text()
|
275 |
-
target_language_combobox = self.target_language_combobox.currentText()
|
276 |
-
target_language_combobox = i18n(target_language_combobox)
|
277 |
-
target_text = self.target_text_input.text()
|
278 |
-
output_path = self.output_input.text()
|
279 |
-
|
280 |
-
if GPT_model_path != self.GPT_Path:
|
281 |
-
change_gpt_weights(gpt_path=GPT_model_path)
|
282 |
-
self.GPT_Path = GPT_model_path
|
283 |
-
if SoVITS_model_path != self.SoVITS_Path:
|
284 |
-
change_sovits_weights(sovits_path=SoVITS_model_path)
|
285 |
-
self.SoVITS_Path = SoVITS_model_path
|
286 |
-
|
287 |
-
synthesis_result = get_tts_wav(ref_wav_path=ref_audio_path,
|
288 |
-
prompt_text=ref_text,
|
289 |
-
prompt_language=language_combobox,
|
290 |
-
text=target_text,
|
291 |
-
text_language=target_language_combobox)
|
292 |
-
|
293 |
-
result_list = list(synthesis_result)
|
294 |
-
|
295 |
-
if result_list:
|
296 |
-
last_sampling_rate, last_audio_data = result_list[-1]
|
297 |
-
output_wav_path = os.path.join(output_path, "output.wav")
|
298 |
-
sf.write(output_wav_path, last_audio_data, last_sampling_rate)
|
299 |
-
|
300 |
-
result = "Audio saved to " + output_wav_path
|
301 |
-
|
302 |
-
self.status_bar.showMessage("合成完成!输出路径:" + output_wav_path, 5000)
|
303 |
-
self.output_text.append("处理结果:\n" + result)
|
304 |
-
|
305 |
-
|
306 |
-
if __name__ == '__main__':
|
307 |
-
app = QApplication(sys.argv)
|
308 |
-
mainWin = GPTSoVITSGUI()
|
309 |
-
mainWin.show()
|
310 |
-
sys.exit(app.exec_())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
onnx_export.py
DELETED
@@ -1,334 +0,0 @@
|
|
1 |
-
from module.models_onnx import SynthesizerTrn, symbols
|
2 |
-
from AR.models.t2s_lightning_module_onnx import Text2SemanticLightningModule
|
3 |
-
import torch
|
4 |
-
import torchaudio
|
5 |
-
from torch import nn
|
6 |
-
from feature_extractor import cnhubert
|
7 |
-
cnhubert_base_path = "pretrained_models/chinese-hubert-base"
|
8 |
-
cnhubert.cnhubert_base_path=cnhubert_base_path
|
9 |
-
ssl_model = cnhubert.get_model()
|
10 |
-
from text import cleaned_text_to_sequence
|
11 |
-
import soundfile
|
12 |
-
from tools.my_utils import load_audio
|
13 |
-
import os
|
14 |
-
import json
|
15 |
-
|
16 |
-
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
|
17 |
-
hann_window = torch.hann_window(win_size).to(
|
18 |
-
dtype=y.dtype, device=y.device
|
19 |
-
)
|
20 |
-
y = torch.nn.functional.pad(
|
21 |
-
y.unsqueeze(1),
|
22 |
-
(int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
|
23 |
-
mode="reflect",
|
24 |
-
)
|
25 |
-
y = y.squeeze(1)
|
26 |
-
spec = torch.stft(
|
27 |
-
y,
|
28 |
-
n_fft,
|
29 |
-
hop_length=hop_size,
|
30 |
-
win_length=win_size,
|
31 |
-
window=hann_window,
|
32 |
-
center=center,
|
33 |
-
pad_mode="reflect",
|
34 |
-
normalized=False,
|
35 |
-
onesided=True,
|
36 |
-
return_complex=False,
|
37 |
-
)
|
38 |
-
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
39 |
-
return spec
|
40 |
-
|
41 |
-
|
42 |
-
class DictToAttrRecursive(dict):
|
43 |
-
def __init__(self, input_dict):
|
44 |
-
super().__init__(input_dict)
|
45 |
-
for key, value in input_dict.items():
|
46 |
-
if isinstance(value, dict):
|
47 |
-
value = DictToAttrRecursive(value)
|
48 |
-
self[key] = value
|
49 |
-
setattr(self, key, value)
|
50 |
-
|
51 |
-
def __getattr__(self, item):
|
52 |
-
try:
|
53 |
-
return self[item]
|
54 |
-
except KeyError:
|
55 |
-
raise AttributeError(f"Attribute {item} not found")
|
56 |
-
|
57 |
-
def __setattr__(self, key, value):
|
58 |
-
if isinstance(value, dict):
|
59 |
-
value = DictToAttrRecursive(value)
|
60 |
-
super(DictToAttrRecursive, self).__setitem__(key, value)
|
61 |
-
super().__setattr__(key, value)
|
62 |
-
|
63 |
-
def __delattr__(self, item):
|
64 |
-
try:
|
65 |
-
del self[item]
|
66 |
-
except KeyError:
|
67 |
-
raise AttributeError(f"Attribute {item} not found")
|
68 |
-
|
69 |
-
|
70 |
-
class T2SEncoder(nn.Module):
|
71 |
-
def __init__(self, t2s, vits):
|
72 |
-
super().__init__()
|
73 |
-
self.encoder = t2s.onnx_encoder
|
74 |
-
self.vits = vits
|
75 |
-
|
76 |
-
def forward(self, ref_seq, text_seq, ref_bert, text_bert, ssl_content):
|
77 |
-
codes = self.vits.extract_latent(ssl_content)
|
78 |
-
prompt_semantic = codes[0, 0]
|
79 |
-
bert = torch.cat([ref_bert.transpose(0, 1), text_bert.transpose(0, 1)], 1)
|
80 |
-
all_phoneme_ids = torch.cat([ref_seq, text_seq], 1)
|
81 |
-
bert = bert.unsqueeze(0)
|
82 |
-
prompt = prompt_semantic.unsqueeze(0)
|
83 |
-
return self.encoder(all_phoneme_ids, bert), prompt
|
84 |
-
|
85 |
-
|
86 |
-
class T2SModel(nn.Module):
|
87 |
-
def __init__(self, t2s_path, vits_model):
|
88 |
-
super().__init__()
|
89 |
-
dict_s1 = torch.load(t2s_path, map_location="cpu")
|
90 |
-
self.config = dict_s1["config"]
|
91 |
-
self.t2s_model = Text2SemanticLightningModule(self.config, "ojbk", is_train=False)
|
92 |
-
self.t2s_model.load_state_dict(dict_s1["weight"])
|
93 |
-
self.t2s_model.eval()
|
94 |
-
self.vits_model = vits_model.vq_model
|
95 |
-
self.hz = 50
|
96 |
-
self.max_sec = self.config["data"]["max_sec"]
|
97 |
-
self.t2s_model.model.top_k = torch.LongTensor([self.config["inference"]["top_k"]])
|
98 |
-
self.t2s_model.model.early_stop_num = torch.LongTensor([self.hz * self.max_sec])
|
99 |
-
self.t2s_model = self.t2s_model.model
|
100 |
-
self.t2s_model.init_onnx()
|
101 |
-
self.onnx_encoder = T2SEncoder(self.t2s_model, self.vits_model)
|
102 |
-
self.first_stage_decoder = self.t2s_model.first_stage_decoder
|
103 |
-
self.stage_decoder = self.t2s_model.stage_decoder
|
104 |
-
#self.t2s_model = torch.jit.script(self.t2s_model)
|
105 |
-
|
106 |
-
def forward(self, ref_seq, text_seq, ref_bert, text_bert, ssl_content):
|
107 |
-
early_stop_num = self.t2s_model.early_stop_num
|
108 |
-
|
109 |
-
#[1,N] [1,N] [N, 1024] [N, 1024] [1, 768, N]
|
110 |
-
x, prompts = self.onnx_encoder(ref_seq, text_seq, ref_bert, text_bert, ssl_content)
|
111 |
-
|
112 |
-
prefix_len = prompts.shape[1]
|
113 |
-
|
114 |
-
#[1,N,512] [1,N]
|
115 |
-
y, k, v, y_emb, x_example = self.first_stage_decoder(x, prompts)
|
116 |
-
|
117 |
-
stop = False
|
118 |
-
for idx in range(1, 1500):
|
119 |
-
#[1, N] [N_layer, N, 1, 512] [N_layer, N, 1, 512] [1, N, 512] [1] [1, N, 512] [1, N]
|
120 |
-
enco = self.stage_decoder(y, k, v, y_emb, x_example)
|
121 |
-
y, k, v, y_emb, logits, samples = enco
|
122 |
-
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
123 |
-
stop = True
|
124 |
-
if torch.argmax(logits, dim=-1)[0] == self.t2s_model.EOS or samples[0, 0] == self.t2s_model.EOS:
|
125 |
-
stop = True
|
126 |
-
if stop:
|
127 |
-
break
|
128 |
-
y[0, -1] = 0
|
129 |
-
|
130 |
-
return y[:, -idx:].unsqueeze(0)
|
131 |
-
|
132 |
-
def export(self, ref_seq, text_seq, ref_bert, text_bert, ssl_content, project_name, dynamo=False):
|
133 |
-
#self.onnx_encoder = torch.jit.script(self.onnx_encoder)
|
134 |
-
if dynamo:
|
135 |
-
export_options = torch.onnx.ExportOptions(dynamic_shapes=True)
|
136 |
-
onnx_encoder_export_output = torch.onnx.dynamo_export(
|
137 |
-
self.onnx_encoder,
|
138 |
-
(ref_seq, text_seq, ref_bert, text_bert, ssl_content),
|
139 |
-
export_options=export_options
|
140 |
-
)
|
141 |
-
onnx_encoder_export_output.save(f"onnx/{project_name}/{project_name}_t2s_encoder.onnx")
|
142 |
-
return
|
143 |
-
|
144 |
-
torch.onnx.export(
|
145 |
-
self.onnx_encoder,
|
146 |
-
(ref_seq, text_seq, ref_bert, text_bert, ssl_content),
|
147 |
-
f"onnx/{project_name}/{project_name}_t2s_encoder.onnx",
|
148 |
-
input_names=["ref_seq", "text_seq", "ref_bert", "text_bert", "ssl_content"],
|
149 |
-
output_names=["x", "prompts"],
|
150 |
-
dynamic_axes={
|
151 |
-
"ref_seq": {1 : "ref_length"},
|
152 |
-
"text_seq": {1 : "text_length"},
|
153 |
-
"ref_bert": {0 : "ref_length"},
|
154 |
-
"text_bert": {0 : "text_length"},
|
155 |
-
"ssl_content": {2 : "ssl_length"},
|
156 |
-
},
|
157 |
-
opset_version=16
|
158 |
-
)
|
159 |
-
x, prompts = self.onnx_encoder(ref_seq, text_seq, ref_bert, text_bert, ssl_content)
|
160 |
-
|
161 |
-
torch.onnx.export(
|
162 |
-
self.first_stage_decoder,
|
163 |
-
(x, prompts),
|
164 |
-
f"onnx/{project_name}/{project_name}_t2s_fsdec.onnx",
|
165 |
-
input_names=["x", "prompts"],
|
166 |
-
output_names=["y", "k", "v", "y_emb", "x_example"],
|
167 |
-
dynamic_axes={
|
168 |
-
"x": {1 : "x_length"},
|
169 |
-
"prompts": {1 : "prompts_length"},
|
170 |
-
},
|
171 |
-
verbose=False,
|
172 |
-
opset_version=16
|
173 |
-
)
|
174 |
-
y, k, v, y_emb, x_example = self.first_stage_decoder(x, prompts)
|
175 |
-
|
176 |
-
torch.onnx.export(
|
177 |
-
self.stage_decoder,
|
178 |
-
(y, k, v, y_emb, x_example),
|
179 |
-
f"onnx/{project_name}/{project_name}_t2s_sdec.onnx",
|
180 |
-
input_names=["iy", "ik", "iv", "iy_emb", "ix_example"],
|
181 |
-
output_names=["y", "k", "v", "y_emb", "logits", "samples"],
|
182 |
-
dynamic_axes={
|
183 |
-
"iy": {1 : "iy_length"},
|
184 |
-
"ik": {1 : "ik_length"},
|
185 |
-
"iv": {1 : "iv_length"},
|
186 |
-
"iy_emb": {1 : "iy_emb_length"},
|
187 |
-
"ix_example": {1 : "ix_example_length"},
|
188 |
-
},
|
189 |
-
verbose=False,
|
190 |
-
opset_version=16
|
191 |
-
)
|
192 |
-
|
193 |
-
|
194 |
-
class VitsModel(nn.Module):
|
195 |
-
def __init__(self, vits_path):
|
196 |
-
super().__init__()
|
197 |
-
dict_s2 = torch.load(vits_path,map_location="cpu")
|
198 |
-
self.hps = dict_s2["config"]
|
199 |
-
self.hps = DictToAttrRecursive(self.hps)
|
200 |
-
self.hps.model.semantic_frame_rate = "25hz"
|
201 |
-
self.vq_model = SynthesizerTrn(
|
202 |
-
self.hps.data.filter_length // 2 + 1,
|
203 |
-
self.hps.train.segment_size // self.hps.data.hop_length,
|
204 |
-
n_speakers=self.hps.data.n_speakers,
|
205 |
-
**self.hps.model
|
206 |
-
)
|
207 |
-
self.vq_model.eval()
|
208 |
-
self.vq_model.load_state_dict(dict_s2["weight"], strict=False)
|
209 |
-
|
210 |
-
def forward(self, text_seq, pred_semantic, ref_audio):
|
211 |
-
refer = spectrogram_torch(
|
212 |
-
ref_audio,
|
213 |
-
self.hps.data.filter_length,
|
214 |
-
self.hps.data.sampling_rate,
|
215 |
-
self.hps.data.hop_length,
|
216 |
-
self.hps.data.win_length,
|
217 |
-
center=False
|
218 |
-
)
|
219 |
-
return self.vq_model(pred_semantic, text_seq, refer)[0, 0]
|
220 |
-
|
221 |
-
|
222 |
-
class GptSoVits(nn.Module):
|
223 |
-
def __init__(self, vits, t2s):
|
224 |
-
super().__init__()
|
225 |
-
self.vits = vits
|
226 |
-
self.t2s = t2s
|
227 |
-
|
228 |
-
def forward(self, ref_seq, text_seq, ref_bert, text_bert, ref_audio, ssl_content, debug=False):
|
229 |
-
pred_semantic = self.t2s(ref_seq, text_seq, ref_bert, text_bert, ssl_content)
|
230 |
-
audio = self.vits(text_seq, pred_semantic, ref_audio)
|
231 |
-
if debug:
|
232 |
-
import onnxruntime
|
233 |
-
sess = onnxruntime.InferenceSession("onnx/koharu/koharu_vits.onnx", providers=["CPU"])
|
234 |
-
audio1 = sess.run(None, {
|
235 |
-
"text_seq" : text_seq.detach().cpu().numpy(),
|
236 |
-
"pred_semantic" : pred_semantic.detach().cpu().numpy(),
|
237 |
-
"ref_audio" : ref_audio.detach().cpu().numpy()
|
238 |
-
})
|
239 |
-
return audio, audio1
|
240 |
-
return audio
|
241 |
-
|
242 |
-
def export(self, ref_seq, text_seq, ref_bert, text_bert, ref_audio, ssl_content, project_name):
|
243 |
-
self.t2s.export(ref_seq, text_seq, ref_bert, text_bert, ssl_content, project_name)
|
244 |
-
pred_semantic = self.t2s(ref_seq, text_seq, ref_bert, text_bert, ssl_content)
|
245 |
-
torch.onnx.export(
|
246 |
-
self.vits,
|
247 |
-
(text_seq, pred_semantic, ref_audio),
|
248 |
-
f"onnx/{project_name}/{project_name}_vits.onnx",
|
249 |
-
input_names=["text_seq", "pred_semantic", "ref_audio"],
|
250 |
-
output_names=["audio"],
|
251 |
-
dynamic_axes={
|
252 |
-
"text_seq": {1 : "text_length"},
|
253 |
-
"pred_semantic": {2 : "pred_length"},
|
254 |
-
"ref_audio": {1 : "audio_length"},
|
255 |
-
},
|
256 |
-
opset_version=17,
|
257 |
-
verbose=False
|
258 |
-
)
|
259 |
-
|
260 |
-
|
261 |
-
class SSLModel(nn.Module):
|
262 |
-
def __init__(self):
|
263 |
-
super().__init__()
|
264 |
-
self.ssl = ssl_model
|
265 |
-
|
266 |
-
def forward(self, ref_audio_16k):
|
267 |
-
return self.ssl.model(ref_audio_16k)["last_hidden_state"].transpose(1, 2)
|
268 |
-
|
269 |
-
|
270 |
-
def export(vits_path, gpt_path, project_name):
|
271 |
-
vits = VitsModel(vits_path)
|
272 |
-
gpt = T2SModel(gpt_path, vits)
|
273 |
-
gpt_sovits = GptSoVits(vits, gpt)
|
274 |
-
ssl = SSLModel()
|
275 |
-
ref_seq = torch.LongTensor([cleaned_text_to_sequence(["n", "i2", "h", "ao3", ",", "w", "o3", "sh", "i4", "b", "ai2", "y", "e4"])])
|
276 |
-
text_seq = torch.LongTensor([cleaned_text_to_sequence(["w", "o3", "sh", "i4", "b", "ai2", "y", "e4", "w", "o3", "sh", "i4", "b", "ai2", "y", "e4", "w", "o3", "sh", "i4", "b", "ai2", "y", "e4"])])
|
277 |
-
ref_bert = torch.randn((ref_seq.shape[1], 1024)).float()
|
278 |
-
text_bert = torch.randn((text_seq.shape[1], 1024)).float()
|
279 |
-
ref_audio = torch.randn((1, 48000 * 5)).float()
|
280 |
-
# ref_audio = torch.tensor([load_audio("rec.wav", 48000)]).float()
|
281 |
-
ref_audio_16k = torchaudio.functional.resample(ref_audio,48000,16000).float()
|
282 |
-
ref_audio_sr = torchaudio.functional.resample(ref_audio,48000,vits.hps.data.sampling_rate).float()
|
283 |
-
|
284 |
-
try:
|
285 |
-
os.mkdir(f"onnx/{project_name}")
|
286 |
-
except:
|
287 |
-
pass
|
288 |
-
|
289 |
-
ssl_content = ssl(ref_audio_16k).float()
|
290 |
-
|
291 |
-
debug = False
|
292 |
-
|
293 |
-
if debug:
|
294 |
-
a, b = gpt_sovits(ref_seq, text_seq, ref_bert, text_bert, ref_audio_sr, ssl_content, debug=debug)
|
295 |
-
soundfile.write("out1.wav", a.cpu().detach().numpy(), vits.hps.data.sampling_rate)
|
296 |
-
soundfile.write("out2.wav", b[0], vits.hps.data.sampling_rate)
|
297 |
-
return
|
298 |
-
|
299 |
-
a = gpt_sovits(ref_seq, text_seq, ref_bert, text_bert, ref_audio_sr, ssl_content).detach().cpu().numpy()
|
300 |
-
|
301 |
-
soundfile.write("out.wav", a, vits.hps.data.sampling_rate)
|
302 |
-
|
303 |
-
gpt_sovits.export(ref_seq, text_seq, ref_bert, text_bert, ref_audio_sr, ssl_content, project_name)
|
304 |
-
|
305 |
-
MoeVSConf = {
|
306 |
-
"Folder" : f"{project_name}",
|
307 |
-
"Name" : f"{project_name}",
|
308 |
-
"Type" : "GPT-SoVits",
|
309 |
-
"Rate" : vits.hps.data.sampling_rate,
|
310 |
-
"NumLayers": gpt.t2s_model.num_layers,
|
311 |
-
"EmbeddingDim": gpt.t2s_model.embedding_dim,
|
312 |
-
"Dict": "BasicDict",
|
313 |
-
"BertPath": "chinese-roberta-wwm-ext-large",
|
314 |
-
"Symbol": symbols,
|
315 |
-
"AddBlank": False
|
316 |
-
}
|
317 |
-
|
318 |
-
MoeVSConfJson = json.dumps(MoeVSConf)
|
319 |
-
with open(f"onnx/{project_name}.json", 'w') as MoeVsConfFile:
|
320 |
-
json.dump(MoeVSConf, MoeVsConfFile, indent = 4)
|
321 |
-
|
322 |
-
|
323 |
-
if __name__ == "__main__":
|
324 |
-
try:
|
325 |
-
os.mkdir("onnx")
|
326 |
-
except:
|
327 |
-
pass
|
328 |
-
|
329 |
-
gpt_path = "GPT_weights/nahida-e25.ckpt"
|
330 |
-
vits_path = "SoVITS_weights/nahida_e30_s3930.pth"
|
331 |
-
exp_path = "nahida"
|
332 |
-
export(vits_path, gpt_path, exp_path)
|
333 |
-
|
334 |
-
# soundfile.write("out.wav", a, vits.hps.data.sampling_rate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prepare_datasets/1-get-text.py
DELETED
@@ -1,146 +0,0 @@
|
|
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 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ.get("_CUDA_VISIBLE_DEVICES")
|
11 |
-
opt_dir = os.environ.get("opt_dir")
|
12 |
-
bert_pretrained_dir = os.environ.get("bert_pretrained_dir")
|
13 |
-
import torch
|
14 |
-
is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
|
15 |
-
version = os.environ.get('version', None)
|
16 |
-
import sys, numpy as np, traceback, pdb
|
17 |
-
import os.path
|
18 |
-
from glob import glob
|
19 |
-
from tqdm import tqdm
|
20 |
-
from text.cleaner import clean_text
|
21 |
-
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
22 |
-
import numpy as np
|
23 |
-
from tools.my_utils import clean_path
|
24 |
-
|
25 |
-
# inp_text=sys.argv[1]
|
26 |
-
# inp_wav_dir=sys.argv[2]
|
27 |
-
# exp_name=sys.argv[3]
|
28 |
-
# i_part=sys.argv[4]
|
29 |
-
# all_parts=sys.argv[5]
|
30 |
-
# os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[6]#i_gpu
|
31 |
-
# opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
|
32 |
-
# bert_pretrained_dir="/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large"
|
33 |
-
|
34 |
-
from time import time as ttime
|
35 |
-
import shutil
|
36 |
-
|
37 |
-
|
38 |
-
def my_save(fea,path):#####fix issue: torch.save doesn't support chinese path
|
39 |
-
dir=os.path.dirname(path)
|
40 |
-
name=os.path.basename(path)
|
41 |
-
# tmp_path="%s/%s%s.pth"%(dir,ttime(),i_part)
|
42 |
-
tmp_path="%s%s.pth"%(ttime(),i_part)
|
43 |
-
torch.save(fea,tmp_path)
|
44 |
-
shutil.move(tmp_path,"%s/%s"%(dir,name))
|
45 |
-
|
46 |
-
|
47 |
-
txt_path = "%s/2-name2text-%s.txt" % (opt_dir, i_part)
|
48 |
-
if os.path.exists(txt_path) == False:
|
49 |
-
bert_dir = "%s/3-bert" % (opt_dir)
|
50 |
-
os.makedirs(opt_dir, exist_ok=True)
|
51 |
-
os.makedirs(bert_dir, exist_ok=True)
|
52 |
-
if torch.cuda.is_available():
|
53 |
-
device = "cuda:0"
|
54 |
-
# elif torch.backends.mps.is_available():
|
55 |
-
# device = "mps"
|
56 |
-
else:
|
57 |
-
device = "cpu"
|
58 |
-
if os.path.exists(bert_pretrained_dir):...
|
59 |
-
else:raise FileNotFoundError(bert_pretrained_dir)
|
60 |
-
tokenizer = AutoTokenizer.from_pretrained(bert_pretrained_dir)
|
61 |
-
bert_model = AutoModelForMaskedLM.from_pretrained(bert_pretrained_dir)
|
62 |
-
if is_half == True:
|
63 |
-
bert_model = bert_model.half().to(device)
|
64 |
-
else:
|
65 |
-
bert_model = bert_model.to(device)
|
66 |
-
|
67 |
-
def get_bert_feature(text, word2ph):
|
68 |
-
with torch.no_grad():
|
69 |
-
inputs = tokenizer(text, return_tensors="pt")
|
70 |
-
for i in inputs:
|
71 |
-
inputs[i] = inputs[i].to(device)
|
72 |
-
res = bert_model(**inputs, output_hidden_states=True)
|
73 |
-
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
|
74 |
-
|
75 |
-
assert len(word2ph) == len(text)
|
76 |
-
phone_level_feature = []
|
77 |
-
for i in range(len(word2ph)):
|
78 |
-
repeat_feature = res[i].repeat(word2ph[i], 1)
|
79 |
-
phone_level_feature.append(repeat_feature)
|
80 |
-
|
81 |
-
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
82 |
-
|
83 |
-
return phone_level_feature.T
|
84 |
-
|
85 |
-
def process(data, res):
|
86 |
-
for name, text, lan in data:
|
87 |
-
try:
|
88 |
-
name=clean_path(name)
|
89 |
-
name = os.path.basename(name)
|
90 |
-
print(name)
|
91 |
-
phones, word2ph, norm_text = clean_text(
|
92 |
-
text.replace("%", "-").replace("¥", ","), lan, version
|
93 |
-
)
|
94 |
-
path_bert = "%s/%s.pt" % (bert_dir, name)
|
95 |
-
if os.path.exists(path_bert) == False and lan == "zh":
|
96 |
-
bert_feature = get_bert_feature(norm_text, word2ph)
|
97 |
-
assert bert_feature.shape[-1] == len(phones)
|
98 |
-
# torch.save(bert_feature, path_bert)
|
99 |
-
my_save(bert_feature, path_bert)
|
100 |
-
phones = " ".join(phones)
|
101 |
-
# res.append([name,phones])
|
102 |
-
res.append([name, phones, word2ph, norm_text])
|
103 |
-
except:
|
104 |
-
print(name, text, traceback.format_exc())
|
105 |
-
|
106 |
-
todo = []
|
107 |
-
res = []
|
108 |
-
with open(inp_text, "r", encoding="utf8") as f:
|
109 |
-
lines = f.read().strip("\n").split("\n")
|
110 |
-
|
111 |
-
language_v1_to_language_v2 = {
|
112 |
-
"ZH": "zh",
|
113 |
-
"zh": "zh",
|
114 |
-
"JP": "ja",
|
115 |
-
"jp": "ja",
|
116 |
-
"JA": "ja",
|
117 |
-
"ja": "ja",
|
118 |
-
"EN": "en",
|
119 |
-
"en": "en",
|
120 |
-
"En": "en",
|
121 |
-
"KO": "ko",
|
122 |
-
"Ko": "ko",
|
123 |
-
"ko": "ko",
|
124 |
-
"yue": "yue",
|
125 |
-
"YUE": "yue",
|
126 |
-
"Yue": "yue",
|
127 |
-
}
|
128 |
-
for line in lines[int(i_part) :: int(all_parts)]:
|
129 |
-
try:
|
130 |
-
wav_name, spk_name, language, text = line.split("|")
|
131 |
-
# todo.append([name,text,"zh"])
|
132 |
-
if language in language_v1_to_language_v2.keys():
|
133 |
-
todo.append(
|
134 |
-
[wav_name, text, language_v1_to_language_v2.get(language, language)]
|
135 |
-
)
|
136 |
-
else:
|
137 |
-
print(f"\033[33m[Waring] The {language = } of {wav_name} is not supported for training.\033[0m")
|
138 |
-
except:
|
139 |
-
print(line, traceback.format_exc())
|
140 |
-
|
141 |
-
process(todo, res)
|
142 |
-
opt = []
|
143 |
-
for name, phones, word2ph, norm_text in res:
|
144 |
-
opt.append("%s\t%s\t%s\t%s" % (name, phones, word2ph, norm_text))
|
145 |
-
with open(txt_path, "w", encoding="utf8") as f:
|
146 |
-
f.write("\n".join(opt) + "\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prepare_datasets/2-get-hubert-wav32k.py
DELETED
@@ -1,122 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
|
3 |
-
import sys,os
|
4 |
-
inp_text= os.environ.get("inp_text")
|
5 |
-
inp_wav_dir= os.environ.get("inp_wav_dir")
|
6 |
-
exp_name= os.environ.get("exp_name")
|
7 |
-
i_part= os.environ.get("i_part")
|
8 |
-
all_parts= os.environ.get("all_parts")
|
9 |
-
os.environ["CUDA_VISIBLE_DEVICES"]= os.environ.get("_CUDA_VISIBLE_DEVICES")
|
10 |
-
from feature_extractor import cnhubert
|
11 |
-
opt_dir= os.environ.get("opt_dir")
|
12 |
-
cnhubert.cnhubert_base_path= os.environ.get("cnhubert_base_dir")
|
13 |
-
import torch
|
14 |
-
is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
|
15 |
-
|
16 |
-
import pdb,traceback,numpy as np,logging
|
17 |
-
from scipy.io import wavfile
|
18 |
-
import librosa
|
19 |
-
now_dir = os.getcwd()
|
20 |
-
sys.path.append(now_dir)
|
21 |
-
from tools.my_utils import load_audio,clean_path
|
22 |
-
|
23 |
-
# from config import cnhubert_base_path
|
24 |
-
# cnhubert.cnhubert_base_path=cnhubert_base_path
|
25 |
-
# inp_text=sys.argv[1]
|
26 |
-
# inp_wav_dir=sys.argv[2]
|
27 |
-
# exp_name=sys.argv[3]
|
28 |
-
# i_part=sys.argv[4]
|
29 |
-
# all_parts=sys.argv[5]
|
30 |
-
# os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[6]
|
31 |
-
# cnhubert.cnhubert_base_path=sys.argv[7]
|
32 |
-
# opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
|
33 |
-
|
34 |
-
from time import time as ttime
|
35 |
-
import shutil
|
36 |
-
def my_save(fea,path):#####fix issue: torch.save doesn't support chinese path
|
37 |
-
dir=os.path.dirname(path)
|
38 |
-
name=os.path.basename(path)
|
39 |
-
# tmp_path="%s/%s%s.pth"%(dir,ttime(),i_part)
|
40 |
-
tmp_path="%s%s.pth"%(ttime(),i_part)
|
41 |
-
torch.save(fea,tmp_path)
|
42 |
-
shutil.move(tmp_path,"%s/%s"%(dir,name))
|
43 |
-
|
44 |
-
hubert_dir="%s/4-cnhubert"%(opt_dir)
|
45 |
-
wav32dir="%s/5-wav32k"%(opt_dir)
|
46 |
-
os.makedirs(opt_dir,exist_ok=True)
|
47 |
-
os.makedirs(hubert_dir,exist_ok=True)
|
48 |
-
os.makedirs(wav32dir,exist_ok=True)
|
49 |
-
|
50 |
-
maxx=0.95
|
51 |
-
alpha=0.5
|
52 |
-
if torch.cuda.is_available():
|
53 |
-
device = "cuda:0"
|
54 |
-
# elif torch.backends.mps.is_available():
|
55 |
-
# device = "mps"
|
56 |
-
else:
|
57 |
-
device = "cpu"
|
58 |
-
model=cnhubert.get_model()
|
59 |
-
# is_half=False
|
60 |
-
if(is_half==True):
|
61 |
-
model=model.half().to(device)
|
62 |
-
else:
|
63 |
-
model = model.to(device)
|
64 |
-
|
65 |
-
nan_fails=[]
|
66 |
-
def name2go(wav_name,wav_path):
|
67 |
-
hubert_path="%s/%s.pt"%(hubert_dir,wav_name)
|
68 |
-
if(os.path.exists(hubert_path)):return
|
69 |
-
tmp_audio = load_audio(wav_path, 32000)
|
70 |
-
tmp_max = np.abs(tmp_audio).max()
|
71 |
-
if tmp_max > 2.2:
|
72 |
-
print("%s-filtered,%s" % (wav_name, tmp_max))
|
73 |
-
return
|
74 |
-
tmp_audio32 = (tmp_audio / tmp_max * (maxx * alpha*32768)) + ((1 - alpha)*32768) * tmp_audio
|
75 |
-
tmp_audio32b = (tmp_audio / tmp_max * (maxx * alpha*1145.14)) + ((1 - alpha)*1145.14) * tmp_audio
|
76 |
-
tmp_audio = librosa.resample(
|
77 |
-
tmp_audio32b, orig_sr=32000, target_sr=16000
|
78 |
-
)#不是重采样问题
|
79 |
-
tensor_wav16 = torch.from_numpy(tmp_audio)
|
80 |
-
if (is_half == True):
|
81 |
-
tensor_wav16=tensor_wav16.half().to(device)
|
82 |
-
else:
|
83 |
-
tensor_wav16 = tensor_wav16.to(device)
|
84 |
-
ssl=model.model(tensor_wav16.unsqueeze(0))["last_hidden_state"].transpose(1,2).cpu()#torch.Size([1, 768, 215])
|
85 |
-
if np.isnan(ssl.detach().numpy()).sum()!= 0:
|
86 |
-
nan_fails.append((wav_name,wav_path))
|
87 |
-
print("nan filtered:%s"%wav_name)
|
88 |
-
return
|
89 |
-
wavfile.write(
|
90 |
-
"%s/%s"%(wav32dir,wav_name),
|
91 |
-
32000,
|
92 |
-
tmp_audio32.astype("int16"),
|
93 |
-
)
|
94 |
-
my_save(ssl,hubert_path)
|
95 |
-
|
96 |
-
with open(inp_text,"r",encoding="utf8")as f:
|
97 |
-
lines=f.read().strip("\n").split("\n")
|
98 |
-
|
99 |
-
for line in lines[int(i_part)::int(all_parts)]:
|
100 |
-
try:
|
101 |
-
# wav_name,text=line.split("\t")
|
102 |
-
wav_name, spk_name, language, text = line.split("|")
|
103 |
-
wav_name=clean_path(wav_name)
|
104 |
-
if (inp_wav_dir != "" and inp_wav_dir != None):
|
105 |
-
wav_name = os.path.basename(wav_name)
|
106 |
-
wav_path = "%s/%s"%(inp_wav_dir, wav_name)
|
107 |
-
|
108 |
-
else:
|
109 |
-
wav_path=wav_name
|
110 |
-
wav_name = os.path.basename(wav_name)
|
111 |
-
name2go(wav_name,wav_path)
|
112 |
-
except:
|
113 |
-
print(line,traceback.format_exc())
|
114 |
-
|
115 |
-
if(len(nan_fails)>0 and is_half==True):
|
116 |
-
is_half=False
|
117 |
-
model=model.float()
|
118 |
-
for wav in nan_fails:
|
119 |
-
try:
|
120 |
-
name2go(wav[0],wav[1])
|
121 |
-
except:
|
122 |
-
print(wav_name,traceback.format_exc())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prepare_datasets/3-get-semantic.py
DELETED
@@ -1,101 +0,0 @@
|
|
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 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ.get("_CUDA_VISIBLE_DEVICES")
|
8 |
-
opt_dir = os.environ.get("opt_dir")
|
9 |
-
pretrained_s2G = os.environ.get("pretrained_s2G")
|
10 |
-
s2config_path = os.environ.get("s2config_path")
|
11 |
-
version=os.environ.get("version","v2")
|
12 |
-
import torch
|
13 |
-
is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
|
14 |
-
import math, traceback
|
15 |
-
import multiprocessing
|
16 |
-
import sys, pdb
|
17 |
-
|
18 |
-
now_dir = os.getcwd()
|
19 |
-
sys.path.append(now_dir)
|
20 |
-
from random import shuffle
|
21 |
-
import torch.multiprocessing as mp
|
22 |
-
from glob import glob
|
23 |
-
from tqdm import tqdm
|
24 |
-
import logging, librosa, utils
|
25 |
-
from module.models import SynthesizerTrn
|
26 |
-
from tools.my_utils import clean_path
|
27 |
-
logging.getLogger("numba").setLevel(logging.WARNING)
|
28 |
-
# from config import pretrained_s2G
|
29 |
-
|
30 |
-
# inp_text=sys.argv[1]
|
31 |
-
# exp_name=sys.argv[2]
|
32 |
-
# i_part=sys.argv[3]
|
33 |
-
# all_parts=sys.argv[4]
|
34 |
-
# os.environ["CUDA_VISIBLE_DEVICES"]=sys.argv[5]
|
35 |
-
# opt_dir="/data/docker/liujing04/gpt-vits/fine_tune_dataset/%s"%exp_name
|
36 |
-
|
37 |
-
if os.path.exists(pretrained_s2G):...
|
38 |
-
else:raise FileNotFoundError(pretrained_s2G)
|
39 |
-
|
40 |
-
hubert_dir = "%s/4-cnhubert" % (opt_dir)
|
41 |
-
semantic_path = "%s/6-name2semantic-%s.tsv" % (opt_dir, i_part)
|
42 |
-
if os.path.exists(semantic_path) == False:
|
43 |
-
os.makedirs(opt_dir, exist_ok=True)
|
44 |
-
|
45 |
-
if torch.cuda.is_available():
|
46 |
-
device = "cuda"
|
47 |
-
# elif torch.backends.mps.is_available():
|
48 |
-
# device = "mps"
|
49 |
-
else:
|
50 |
-
device = "cpu"
|
51 |
-
hps = utils.get_hparams_from_file(s2config_path)
|
52 |
-
vq_model = SynthesizerTrn(
|
53 |
-
hps.data.filter_length // 2 + 1,
|
54 |
-
hps.train.segment_size // hps.data.hop_length,
|
55 |
-
n_speakers=hps.data.n_speakers,
|
56 |
-
version=version,
|
57 |
-
**hps.model
|
58 |
-
)
|
59 |
-
if is_half == True:
|
60 |
-
vq_model = vq_model.half().to(device)
|
61 |
-
else:
|
62 |
-
vq_model = vq_model.to(device)
|
63 |
-
vq_model.eval()
|
64 |
-
# utils.load_checkpoint(utils.latest_checkpoint_path(hps.s2_ckpt_dir, "G_*.pth"), vq_model, None, True)
|
65 |
-
# utils.load_checkpoint(pretrained_s2G, vq_model, None, True)
|
66 |
-
print(
|
67 |
-
vq_model.load_state_dict(
|
68 |
-
torch.load(pretrained_s2G, map_location="cpu")["weight"], strict=False
|
69 |
-
)
|
70 |
-
)
|
71 |
-
|
72 |
-
def name2go(wav_name, lines):
|
73 |
-
hubert_path = "%s/%s.pt" % (hubert_dir, wav_name)
|
74 |
-
if os.path.exists(hubert_path) == False:
|
75 |
-
return
|
76 |
-
ssl_content = torch.load(hubert_path, map_location="cpu")
|
77 |
-
if is_half == True:
|
78 |
-
ssl_content = ssl_content.half().to(device)
|
79 |
-
else:
|
80 |
-
ssl_content = ssl_content.to(device)
|
81 |
-
codes = vq_model.extract_latent(ssl_content)
|
82 |
-
semantic = " ".join([str(i) for i in codes[0, 0, :].tolist()])
|
83 |
-
lines.append("%s\t%s" % (wav_name, semantic))
|
84 |
-
|
85 |
-
with open(inp_text, "r", encoding="utf8") as f:
|
86 |
-
lines = f.read().strip("\n").split("\n")
|
87 |
-
|
88 |
-
lines1 = []
|
89 |
-
for line in lines[int(i_part) :: int(all_parts)]:
|
90 |
-
# print(line)
|
91 |
-
try:
|
92 |
-
# wav_name,text=line.split("\t")
|
93 |
-
wav_name, spk_name, language, text = line.split("|")
|
94 |
-
wav_name=clean_path(wav_name)
|
95 |
-
wav_name = os.path.basename(wav_name)
|
96 |
-
# name2go(name,lines1)
|
97 |
-
name2go(wav_name, lines1)
|
98 |
-
except:
|
99 |
-
print(line, traceback.format_exc())
|
100 |
-
with open(semantic_path, "w", encoding="utf8") as f:
|
101 |
-
f.write("\n".join(lines1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
s1_train.py
DELETED
@@ -1,183 +0,0 @@
|
|
1 |
-
# modified from https://github.com/feng-yufei/shared_debugging_code/blob/main/train_t2s.py
|
2 |
-
import os
|
3 |
-
import pdb
|
4 |
-
|
5 |
-
if "_CUDA_VISIBLE_DEVICES" in os.environ:
|
6 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
|
7 |
-
import argparse
|
8 |
-
import logging
|
9 |
-
from pathlib import Path
|
10 |
-
|
11 |
-
import torch, platform
|
12 |
-
from pytorch_lightning import seed_everything
|
13 |
-
from pytorch_lightning import Trainer
|
14 |
-
from pytorch_lightning.callbacks import ModelCheckpoint
|
15 |
-
from pytorch_lightning.loggers import TensorBoardLogger # WandbLogger
|
16 |
-
from pytorch_lightning.strategies import DDPStrategy
|
17 |
-
from AR.data.data_module import Text2SemanticDataModule
|
18 |
-
from AR.models.t2s_lightning_module import Text2SemanticLightningModule
|
19 |
-
from AR.utils.io import load_yaml_config
|
20 |
-
|
21 |
-
logging.getLogger("numba").setLevel(logging.WARNING)
|
22 |
-
logging.getLogger("matplotlib").setLevel(logging.WARNING)
|
23 |
-
torch.set_float32_matmul_precision("high")
|
24 |
-
from AR.utils import get_newest_ckpt
|
25 |
-
|
26 |
-
from collections import OrderedDict
|
27 |
-
from time import time as ttime
|
28 |
-
import shutil
|
29 |
-
def my_save(fea,path):#####fix issue: torch.save doesn't support chinese path
|
30 |
-
dir=os.path.dirname(path)
|
31 |
-
name=os.path.basename(path)
|
32 |
-
tmp_path="%s.pth"%(ttime())
|
33 |
-
torch.save(fea,tmp_path)
|
34 |
-
shutil.move(tmp_path,"%s/%s"%(dir,name))
|
35 |
-
|
36 |
-
|
37 |
-
class my_model_ckpt(ModelCheckpoint):
|
38 |
-
def __init__(
|
39 |
-
self,
|
40 |
-
config,
|
41 |
-
if_save_latest,
|
42 |
-
if_save_every_weights,
|
43 |
-
half_weights_save_dir,
|
44 |
-
exp_name,
|
45 |
-
**kwargs
|
46 |
-
):
|
47 |
-
super().__init__(**kwargs)
|
48 |
-
self.if_save_latest = if_save_latest
|
49 |
-
self.if_save_every_weights = if_save_every_weights
|
50 |
-
self.half_weights_save_dir = half_weights_save_dir
|
51 |
-
self.exp_name = exp_name
|
52 |
-
self.config = config
|
53 |
-
|
54 |
-
def on_train_epoch_end(self, trainer, pl_module):
|
55 |
-
# if not self._should_skip_saving_checkpoint(trainer) and self._should_save_on_train_epoch_end(trainer):
|
56 |
-
if self._should_save_on_train_epoch_end(trainer):
|
57 |
-
monitor_candidates = self._monitor_candidates(trainer)
|
58 |
-
if (
|
59 |
-
self._every_n_epochs >= 1
|
60 |
-
and (trainer.current_epoch + 1) % self._every_n_epochs == 0
|
61 |
-
):
|
62 |
-
if (
|
63 |
-
self.if_save_latest == True
|
64 |
-
): ####如果设置只保存最后一个ckpt,在保存下一个ckpt后要清理掉之前的所有ckpt
|
65 |
-
to_clean = list(os.listdir(self.dirpath))
|
66 |
-
self._save_topk_checkpoint(trainer, monitor_candidates)
|
67 |
-
if self.if_save_latest == True:
|
68 |
-
for name in to_clean:
|
69 |
-
try:
|
70 |
-
os.remove("%s/%s" % (self.dirpath, name))
|
71 |
-
except:
|
72 |
-
pass
|
73 |
-
if self.if_save_every_weights == True:
|
74 |
-
to_save_od = OrderedDict()
|
75 |
-
to_save_od["weight"] = OrderedDict()
|
76 |
-
dictt = trainer.strategy._lightning_module.state_dict()
|
77 |
-
for key in dictt:
|
78 |
-
to_save_od["weight"][key] = dictt[key].half()
|
79 |
-
to_save_od["config"] = self.config
|
80 |
-
to_save_od["info"] = "GPT-e%s" % (trainer.current_epoch + 1)
|
81 |
-
# torch.save(
|
82 |
-
# print(os.environ)
|
83 |
-
if(os.environ.get("LOCAL_RANK","0")=="0"):
|
84 |
-
my_save(
|
85 |
-
to_save_od,
|
86 |
-
"%s/%s-e%s.ckpt"
|
87 |
-
% (
|
88 |
-
self.half_weights_save_dir,
|
89 |
-
self.exp_name,
|
90 |
-
trainer.current_epoch + 1,
|
91 |
-
),
|
92 |
-
)
|
93 |
-
self._save_last_checkpoint(trainer, monitor_candidates)
|
94 |
-
|
95 |
-
|
96 |
-
def main(args):
|
97 |
-
config = load_yaml_config(args.config_file)
|
98 |
-
|
99 |
-
output_dir = Path(config["output_dir"])
|
100 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
101 |
-
|
102 |
-
ckpt_dir = output_dir / "ckpt"
|
103 |
-
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
104 |
-
|
105 |
-
seed_everything(config["train"]["seed"], workers=True)
|
106 |
-
ckpt_callback: ModelCheckpoint = my_model_ckpt(
|
107 |
-
config=config,
|
108 |
-
if_save_latest=config["train"]["if_save_latest"],
|
109 |
-
if_save_every_weights=config["train"]["if_save_every_weights"],
|
110 |
-
half_weights_save_dir=config["train"]["half_weights_save_dir"],
|
111 |
-
exp_name=config["train"]["exp_name"],
|
112 |
-
save_top_k=-1,
|
113 |
-
monitor="top_3_acc",
|
114 |
-
mode="max",
|
115 |
-
save_on_train_epoch_end=True,
|
116 |
-
every_n_epochs=config["train"]["save_every_n_epoch"],
|
117 |
-
dirpath=ckpt_dir,
|
118 |
-
)
|
119 |
-
logger = TensorBoardLogger(name=output_dir.stem, save_dir=output_dir)
|
120 |
-
os.environ["MASTER_ADDR"]="localhost"
|
121 |
-
trainer: Trainer = Trainer(
|
122 |
-
max_epochs=config["train"]["epochs"],
|
123 |
-
accelerator="gpu" if torch.cuda.is_available() else "cpu",
|
124 |
-
# val_check_interval=9999999999999999999999,###不要验��
|
125 |
-
# check_val_every_n_epoch=None,
|
126 |
-
limit_val_batches=0,
|
127 |
-
devices=-1 if torch.cuda.is_available() else 1,
|
128 |
-
benchmark=False,
|
129 |
-
fast_dev_run=False,
|
130 |
-
strategy = DDPStrategy(
|
131 |
-
process_group_backend="nccl" if platform.system() != "Windows" else "gloo"
|
132 |
-
) if torch.cuda.is_available() else "auto",
|
133 |
-
precision=config["train"]["precision"],
|
134 |
-
logger=logger,
|
135 |
-
num_sanity_val_steps=0,
|
136 |
-
callbacks=[ckpt_callback],
|
137 |
-
use_distributed_sampler=False, # 非常简单的修改,但解决了采用自定义的 bucket_sampler 下训练步数不一致的问题!
|
138 |
-
)
|
139 |
-
|
140 |
-
model: Text2SemanticLightningModule = Text2SemanticLightningModule(
|
141 |
-
config, output_dir
|
142 |
-
)
|
143 |
-
|
144 |
-
data_module: Text2SemanticDataModule = Text2SemanticDataModule(
|
145 |
-
config,
|
146 |
-
train_semantic_path=config["train_semantic_path"],
|
147 |
-
train_phoneme_path=config["train_phoneme_path"],
|
148 |
-
# dev_semantic_path=args.dev_semantic_path,
|
149 |
-
# dev_phoneme_path=args.dev_phoneme_path
|
150 |
-
)
|
151 |
-
|
152 |
-
try:
|
153 |
-
# 使用正则表达式匹配文件名中的数字部分,并按数字大小进行排序
|
154 |
-
newest_ckpt_name = get_newest_ckpt(os.listdir(ckpt_dir))
|
155 |
-
ckpt_path = ckpt_dir / newest_ckpt_name
|
156 |
-
except Exception:
|
157 |
-
ckpt_path = None
|
158 |
-
print("ckpt_path:", ckpt_path)
|
159 |
-
trainer.fit(model, data_module, ckpt_path=ckpt_path)
|
160 |
-
|
161 |
-
|
162 |
-
# srun --gpus-per-node=1 --ntasks-per-node=1 python train.py --path-to-configuration configurations/default.yaml
|
163 |
-
if __name__ == "__main__":
|
164 |
-
parser = argparse.ArgumentParser()
|
165 |
-
parser.add_argument(
|
166 |
-
"-c",
|
167 |
-
"--config_file",
|
168 |
-
type=str,
|
169 |
-
default="configs/s1longer.yaml",
|
170 |
-
help="path of config file",
|
171 |
-
)
|
172 |
-
# args for dataset
|
173 |
-
# parser.add_argument('--train_semantic_path',type=str,default='/data/docker/liujing04/gpt-vits/fine_tune_dataset/xuangou/6-name2semantic.tsv')
|
174 |
-
# parser.add_argument('--train_phoneme_path', type=str, default='/data/docker/liujing04/gpt-vits/fine_tune_dataset/xuangou/2-name2text.txt')
|
175 |
-
|
176 |
-
# parser.add_argument('--dev_semantic_path', type=str, default='dump_mix/semantic_dev.tsv')
|
177 |
-
# parser.add_argument('--dev_phoneme_path', type=str, default='dump_mix/phoneme_dev.npy')
|
178 |
-
# parser.add_argument('--output_dir',type=str,default='/data/docker/liujing04/gpt-vits/fine_tune_dataset/xuangou/logs_s1',help='directory to save the results')
|
179 |
-
# parser.add_argument('--output_dir',type=str,default='/liujing04/gpt_logs/s1/xuangou_ft',help='directory to save the results')
|
180 |
-
|
181 |
-
args = parser.parse_args()
|
182 |
-
logging.info(str(args))
|
183 |
-
main(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
s2_train.py
DELETED
@@ -1,601 +0,0 @@
|
|
1 |
-
import warnings
|
2 |
-
warnings.filterwarnings("ignore")
|
3 |
-
import utils, os
|
4 |
-
hps = utils.get_hparams(stage=2)
|
5 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = hps.train.gpu_numbers.replace("-", ",")
|
6 |
-
import torch
|
7 |
-
from torch.nn import functional as F
|
8 |
-
from torch.utils.data import DataLoader
|
9 |
-
from torch.utils.tensorboard import SummaryWriter
|
10 |
-
import torch.multiprocessing as mp
|
11 |
-
import torch.distributed as dist, traceback
|
12 |
-
from torch.nn.parallel import DistributedDataParallel as DDP
|
13 |
-
from torch.cuda.amp import autocast, GradScaler
|
14 |
-
from tqdm import tqdm
|
15 |
-
import logging, traceback
|
16 |
-
|
17 |
-
logging.getLogger("matplotlib").setLevel(logging.INFO)
|
18 |
-
logging.getLogger("h5py").setLevel(logging.INFO)
|
19 |
-
logging.getLogger("numba").setLevel(logging.INFO)
|
20 |
-
from random import randint
|
21 |
-
from module import commons
|
22 |
-
|
23 |
-
from module.data_utils import (
|
24 |
-
TextAudioSpeakerLoader,
|
25 |
-
TextAudioSpeakerCollate,
|
26 |
-
DistributedBucketSampler,
|
27 |
-
)
|
28 |
-
from module.models import (
|
29 |
-
SynthesizerTrn,
|
30 |
-
MultiPeriodDiscriminator,
|
31 |
-
)
|
32 |
-
from module.losses import generator_loss, discriminator_loss, feature_loss, kl_loss
|
33 |
-
from module.mel_processing import mel_spectrogram_torch, spec_to_mel_torch
|
34 |
-
from process_ckpt import savee
|
35 |
-
|
36 |
-
torch.backends.cudnn.benchmark = False
|
37 |
-
torch.backends.cudnn.deterministic = False
|
38 |
-
###反正A100fp32更快,那试试tf32吧
|
39 |
-
torch.backends.cuda.matmul.allow_tf32 = True
|
40 |
-
torch.backends.cudnn.allow_tf32 = True
|
41 |
-
torch.set_float32_matmul_precision("medium") # 最低精度但最快(也就快一丁点),对于结果造成不了影响
|
42 |
-
# from config import pretrained_s2G,pretrained_s2D
|
43 |
-
global_step = 0
|
44 |
-
|
45 |
-
device = "cpu" # cuda以外的设备,等mps优化后加入
|
46 |
-
|
47 |
-
|
48 |
-
def main():
|
49 |
-
|
50 |
-
if torch.cuda.is_available():
|
51 |
-
n_gpus = torch.cuda.device_count()
|
52 |
-
else:
|
53 |
-
n_gpus = 1
|
54 |
-
os.environ["MASTER_ADDR"] = "localhost"
|
55 |
-
os.environ["MASTER_PORT"] = str(randint(20000, 55555))
|
56 |
-
|
57 |
-
mp.spawn(
|
58 |
-
run,
|
59 |
-
nprocs=n_gpus,
|
60 |
-
args=(
|
61 |
-
n_gpus,
|
62 |
-
hps,
|
63 |
-
),
|
64 |
-
)
|
65 |
-
|
66 |
-
|
67 |
-
def run(rank, n_gpus, hps):
|
68 |
-
global global_step
|
69 |
-
if rank == 0:
|
70 |
-
logger = utils.get_logger(hps.data.exp_dir)
|
71 |
-
logger.info(hps)
|
72 |
-
# utils.check_git_hash(hps.s2_ckpt_dir)
|
73 |
-
writer = SummaryWriter(log_dir=hps.s2_ckpt_dir)
|
74 |
-
writer_eval = SummaryWriter(log_dir=os.path.join(hps.s2_ckpt_dir, "eval"))
|
75 |
-
|
76 |
-
dist.init_process_group(
|
77 |
-
backend = "gloo" if os.name == "nt" or not torch.cuda.is_available() else "nccl",
|
78 |
-
init_method="env://",
|
79 |
-
world_size=n_gpus,
|
80 |
-
rank=rank,
|
81 |
-
)
|
82 |
-
torch.manual_seed(hps.train.seed)
|
83 |
-
if torch.cuda.is_available():
|
84 |
-
torch.cuda.set_device(rank)
|
85 |
-
|
86 |
-
train_dataset = TextAudioSpeakerLoader(hps.data) ########
|
87 |
-
train_sampler = DistributedBucketSampler(
|
88 |
-
train_dataset,
|
89 |
-
hps.train.batch_size,
|
90 |
-
[
|
91 |
-
32,
|
92 |
-
300,
|
93 |
-
400,
|
94 |
-
500,
|
95 |
-
600,
|
96 |
-
700,
|
97 |
-
800,
|
98 |
-
900,
|
99 |
-
1000,
|
100 |
-
1100,
|
101 |
-
1200,
|
102 |
-
1300,
|
103 |
-
1400,
|
104 |
-
1500,
|
105 |
-
1600,
|
106 |
-
1700,
|
107 |
-
1800,
|
108 |
-
1900,
|
109 |
-
],
|
110 |
-
num_replicas=n_gpus,
|
111 |
-
rank=rank,
|
112 |
-
shuffle=True,
|
113 |
-
)
|
114 |
-
collate_fn = TextAudioSpeakerCollate()
|
115 |
-
train_loader = DataLoader(
|
116 |
-
train_dataset,
|
117 |
-
num_workers=6,
|
118 |
-
shuffle=False,
|
119 |
-
pin_memory=True,
|
120 |
-
collate_fn=collate_fn,
|
121 |
-
batch_sampler=train_sampler,
|
122 |
-
persistent_workers=True,
|
123 |
-
prefetch_factor=4,
|
124 |
-
)
|
125 |
-
# if rank == 0:
|
126 |
-
# eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data, val=True)
|
127 |
-
# eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False,
|
128 |
-
# batch_size=1, pin_memory=True,
|
129 |
-
# drop_last=False, collate_fn=collate_fn)
|
130 |
-
|
131 |
-
net_g = SynthesizerTrn(
|
132 |
-
hps.data.filter_length // 2 + 1,
|
133 |
-
hps.train.segment_size // hps.data.hop_length,
|
134 |
-
n_speakers=hps.data.n_speakers,
|
135 |
-
**hps.model,
|
136 |
-
).cuda(rank) if torch.cuda.is_available() else SynthesizerTrn(
|
137 |
-
hps.data.filter_length // 2 + 1,
|
138 |
-
hps.train.segment_size // hps.data.hop_length,
|
139 |
-
n_speakers=hps.data.n_speakers,
|
140 |
-
**hps.model,
|
141 |
-
).to(device)
|
142 |
-
|
143 |
-
net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) if torch.cuda.is_available() else MultiPeriodDiscriminator(hps.model.use_spectral_norm).to(device)
|
144 |
-
for name, param in net_g.named_parameters():
|
145 |
-
if not param.requires_grad:
|
146 |
-
print(name, "not requires_grad")
|
147 |
-
|
148 |
-
te_p = list(map(id, net_g.enc_p.text_embedding.parameters()))
|
149 |
-
et_p = list(map(id, net_g.enc_p.encoder_text.parameters()))
|
150 |
-
mrte_p = list(map(id, net_g.enc_p.mrte.parameters()))
|
151 |
-
base_params = filter(
|
152 |
-
lambda p: id(p) not in te_p + et_p + mrte_p and p.requires_grad,
|
153 |
-
net_g.parameters(),
|
154 |
-
)
|
155 |
-
|
156 |
-
# te_p=net_g.enc_p.text_embedding.parameters()
|
157 |
-
# et_p=net_g.enc_p.encoder_text.parameters()
|
158 |
-
# mrte_p=net_g.enc_p.mrte.parameters()
|
159 |
-
|
160 |
-
optim_g = torch.optim.AdamW(
|
161 |
-
# filter(lambda p: p.requires_grad, net_g.parameters()),###默认所有层lr一致
|
162 |
-
[
|
163 |
-
{"params": base_params, "lr": hps.train.learning_rate},
|
164 |
-
{
|
165 |
-
"params": net_g.enc_p.text_embedding.parameters(),
|
166 |
-
"lr": hps.train.learning_rate * hps.train.text_low_lr_rate,
|
167 |
-
},
|
168 |
-
{
|
169 |
-
"params": net_g.enc_p.encoder_text.parameters(),
|
170 |
-
"lr": hps.train.learning_rate * hps.train.text_low_lr_rate,
|
171 |
-
},
|
172 |
-
{
|
173 |
-
"params": net_g.enc_p.mrte.parameters(),
|
174 |
-
"lr": hps.train.learning_rate * hps.train.text_low_lr_rate,
|
175 |
-
},
|
176 |
-
],
|
177 |
-
hps.train.learning_rate,
|
178 |
-
betas=hps.train.betas,
|
179 |
-
eps=hps.train.eps,
|
180 |
-
)
|
181 |
-
optim_d = torch.optim.AdamW(
|
182 |
-
net_d.parameters(),
|
183 |
-
hps.train.learning_rate,
|
184 |
-
betas=hps.train.betas,
|
185 |
-
eps=hps.train.eps,
|
186 |
-
)
|
187 |
-
if torch.cuda.is_available():
|
188 |
-
net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True)
|
189 |
-
net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True)
|
190 |
-
else:
|
191 |
-
net_g = net_g.to(device)
|
192 |
-
net_d = net_d.to(device)
|
193 |
-
|
194 |
-
try: # 如果能加载自动resume
|
195 |
-
_, _, _, epoch_str = utils.load_checkpoint(
|
196 |
-
utils.latest_checkpoint_path("%s/logs_s2" % hps.data.exp_dir, "D_*.pth"),
|
197 |
-
net_d,
|
198 |
-
optim_d,
|
199 |
-
) # D多半加载没事
|
200 |
-
if rank == 0:
|
201 |
-
logger.info("loaded D")
|
202 |
-
# _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g,load_opt=0)
|
203 |
-
_, _, _, epoch_str = utils.load_checkpoint(
|
204 |
-
utils.latest_checkpoint_path("%s/logs_s2" % hps.data.exp_dir, "G_*.pth"),
|
205 |
-
net_g,
|
206 |
-
optim_g,
|
207 |
-
)
|
208 |
-
global_step = (epoch_str - 1) * len(train_loader)
|
209 |
-
# epoch_str = 1
|
210 |
-
# global_step = 0
|
211 |
-
except: # 如果首次不能加载,加载pretrain
|
212 |
-
# traceback.print_exc()
|
213 |
-
epoch_str = 1
|
214 |
-
global_step = 0
|
215 |
-
if hps.train.pretrained_s2G != ""and hps.train.pretrained_s2G != None and os.path.exists(hps.train.pretrained_s2G):
|
216 |
-
if rank == 0:
|
217 |
-
logger.info("loaded pretrained %s" % hps.train.pretrained_s2G)
|
218 |
-
print(
|
219 |
-
net_g.module.load_state_dict(
|
220 |
-
torch.load(hps.train.pretrained_s2G, map_location="cpu")["weight"],
|
221 |
-
strict=False,
|
222 |
-
) if torch.cuda.is_available() else net_g.load_state_dict(
|
223 |
-
torch.load(hps.train.pretrained_s2G, map_location="cpu")["weight"],
|
224 |
-
strict=False,
|
225 |
-
)
|
226 |
-
) ##测试不加载优化器
|
227 |
-
if hps.train.pretrained_s2D != ""and hps.train.pretrained_s2D != None and os.path.exists(hps.train.pretrained_s2D):
|
228 |
-
if rank == 0:
|
229 |
-
logger.info("loaded pretrained %s" % hps.train.pretrained_s2D)
|
230 |
-
print(
|
231 |
-
net_d.module.load_state_dict(
|
232 |
-
torch.load(hps.train.pretrained_s2D, map_location="cpu")["weight"]
|
233 |
-
) if torch.cuda.is_available() else net_d.load_state_dict(
|
234 |
-
torch.load(hps.train.pretrained_s2D, map_location="cpu")["weight"]
|
235 |
-
)
|
236 |
-
)
|
237 |
-
|
238 |
-
# scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
|
239 |
-
# scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
|
240 |
-
|
241 |
-
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(
|
242 |
-
optim_g, gamma=hps.train.lr_decay, last_epoch=-1
|
243 |
-
)
|
244 |
-
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(
|
245 |
-
optim_d, gamma=hps.train.lr_decay, last_epoch=-1
|
246 |
-
)
|
247 |
-
for _ in range(epoch_str):
|
248 |
-
scheduler_g.step()
|
249 |
-
scheduler_d.step()
|
250 |
-
|
251 |
-
scaler = GradScaler(enabled=hps.train.fp16_run)
|
252 |
-
|
253 |
-
for epoch in range(epoch_str, hps.train.epochs + 1):
|
254 |
-
if rank == 0:
|
255 |
-
train_and_evaluate(
|
256 |
-
rank,
|
257 |
-
epoch,
|
258 |
-
hps,
|
259 |
-
[net_g, net_d],
|
260 |
-
[optim_g, optim_d],
|
261 |
-
[scheduler_g, scheduler_d],
|
262 |
-
scaler,
|
263 |
-
# [train_loader, eval_loader], logger, [writer, writer_eval])
|
264 |
-
[train_loader, None],
|
265 |
-
logger,
|
266 |
-
[writer, writer_eval],
|
267 |
-
)
|
268 |
-
else:
|
269 |
-
train_and_evaluate(
|
270 |
-
rank,
|
271 |
-
epoch,
|
272 |
-
hps,
|
273 |
-
[net_g, net_d],
|
274 |
-
[optim_g, optim_d],
|
275 |
-
[scheduler_g, scheduler_d],
|
276 |
-
scaler,
|
277 |
-
[train_loader, None],
|
278 |
-
None,
|
279 |
-
None,
|
280 |
-
)
|
281 |
-
scheduler_g.step()
|
282 |
-
scheduler_d.step()
|
283 |
-
|
284 |
-
|
285 |
-
def train_and_evaluate(
|
286 |
-
rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers
|
287 |
-
):
|
288 |
-
net_g, net_d = nets
|
289 |
-
optim_g, optim_d = optims
|
290 |
-
# scheduler_g, scheduler_d = schedulers
|
291 |
-
train_loader, eval_loader = loaders
|
292 |
-
if writers is not None:
|
293 |
-
writer, writer_eval = writers
|
294 |
-
|
295 |
-
train_loader.batch_sampler.set_epoch(epoch)
|
296 |
-
global global_step
|
297 |
-
|
298 |
-
net_g.train()
|
299 |
-
net_d.train()
|
300 |
-
for batch_idx, (
|
301 |
-
ssl,
|
302 |
-
ssl_lengths,
|
303 |
-
spec,
|
304 |
-
spec_lengths,
|
305 |
-
y,
|
306 |
-
y_lengths,
|
307 |
-
text,
|
308 |
-
text_lengths,
|
309 |
-
) in enumerate(tqdm(train_loader)):
|
310 |
-
if torch.cuda.is_available():
|
311 |
-
spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(
|
312 |
-
rank, non_blocking=True
|
313 |
-
)
|
314 |
-
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(
|
315 |
-
rank, non_blocking=True
|
316 |
-
)
|
317 |
-
ssl = ssl.cuda(rank, non_blocking=True)
|
318 |
-
ssl.requires_grad = False
|
319 |
-
# ssl_lengths = ssl_lengths.cuda(rank, non_blocking=True)
|
320 |
-
text, text_lengths = text.cuda(rank, non_blocking=True), text_lengths.cuda(
|
321 |
-
rank, non_blocking=True
|
322 |
-
)
|
323 |
-
else:
|
324 |
-
spec, spec_lengths = spec.to(device), spec_lengths.to(device)
|
325 |
-
y, y_lengths = y.to(device), y_lengths.to(device)
|
326 |
-
ssl = ssl.to(device)
|
327 |
-
ssl.requires_grad = False
|
328 |
-
# ssl_lengths = ssl_lengths.cuda(rank, non_blocking=True)
|
329 |
-
text, text_lengths = text.to(device), text_lengths.to(device)
|
330 |
-
|
331 |
-
with autocast(enabled=hps.train.fp16_run):
|
332 |
-
(
|
333 |
-
y_hat,
|
334 |
-
kl_ssl,
|
335 |
-
ids_slice,
|
336 |
-
x_mask,
|
337 |
-
z_mask,
|
338 |
-
(z, z_p, m_p, logs_p, m_q, logs_q),
|
339 |
-
stats_ssl,
|
340 |
-
) = net_g(ssl, spec, spec_lengths, text, text_lengths)
|
341 |
-
|
342 |
-
mel = spec_to_mel_torch(
|
343 |
-
spec,
|
344 |
-
hps.data.filter_length,
|
345 |
-
hps.data.n_mel_channels,
|
346 |
-
hps.data.sampling_rate,
|
347 |
-
hps.data.mel_fmin,
|
348 |
-
hps.data.mel_fmax,
|
349 |
-
)
|
350 |
-
y_mel = commons.slice_segments(
|
351 |
-
mel, ids_slice, hps.train.segment_size // hps.data.hop_length
|
352 |
-
)
|
353 |
-
y_hat_mel = mel_spectrogram_torch(
|
354 |
-
y_hat.squeeze(1),
|
355 |
-
hps.data.filter_length,
|
356 |
-
hps.data.n_mel_channels,
|
357 |
-
hps.data.sampling_rate,
|
358 |
-
hps.data.hop_length,
|
359 |
-
hps.data.win_length,
|
360 |
-
hps.data.mel_fmin,
|
361 |
-
hps.data.mel_fmax,
|
362 |
-
)
|
363 |
-
|
364 |
-
y = commons.slice_segments(
|
365 |
-
y, ids_slice * hps.data.hop_length, hps.train.segment_size
|
366 |
-
) # slice
|
367 |
-
|
368 |
-
# Discriminator
|
369 |
-
y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
|
370 |
-
with autocast(enabled=False):
|
371 |
-
loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(
|
372 |
-
y_d_hat_r, y_d_hat_g
|
373 |
-
)
|
374 |
-
loss_disc_all = loss_disc
|
375 |
-
optim_d.zero_grad()
|
376 |
-
scaler.scale(loss_disc_all).backward()
|
377 |
-
scaler.unscale_(optim_d)
|
378 |
-
grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
|
379 |
-
scaler.step(optim_d)
|
380 |
-
|
381 |
-
with autocast(enabled=hps.train.fp16_run):
|
382 |
-
# Generator
|
383 |
-
y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
|
384 |
-
with autocast(enabled=False):
|
385 |
-
loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
|
386 |
-
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
|
387 |
-
|
388 |
-
loss_fm = feature_loss(fmap_r, fmap_g)
|
389 |
-
loss_gen, losses_gen = generator_loss(y_d_hat_g)
|
390 |
-
loss_gen_all = loss_gen + loss_fm + loss_mel + kl_ssl * 1 + loss_kl
|
391 |
-
|
392 |
-
optim_g.zero_grad()
|
393 |
-
scaler.scale(loss_gen_all).backward()
|
394 |
-
scaler.unscale_(optim_g)
|
395 |
-
grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
|
396 |
-
scaler.step(optim_g)
|
397 |
-
scaler.update()
|
398 |
-
|
399 |
-
if rank == 0:
|
400 |
-
if global_step % hps.train.log_interval == 0:
|
401 |
-
lr = optim_g.param_groups[0]["lr"]
|
402 |
-
losses = [loss_disc, loss_gen, loss_fm, loss_mel, kl_ssl, loss_kl]
|
403 |
-
logger.info(
|
404 |
-
"Train Epoch: {} [{:.0f}%]".format(
|
405 |
-
epoch, 100.0 * batch_idx / len(train_loader)
|
406 |
-
)
|
407 |
-
)
|
408 |
-
logger.info([x.item() for x in losses] + [global_step, lr])
|
409 |
-
|
410 |
-
scalar_dict = {
|
411 |
-
"loss/g/total": loss_gen_all,
|
412 |
-
"loss/d/total": loss_disc_all,
|
413 |
-
"learning_rate": lr,
|
414 |
-
"grad_norm_d": grad_norm_d,
|
415 |
-
"grad_norm_g": grad_norm_g,
|
416 |
-
}
|
417 |
-
scalar_dict.update(
|
418 |
-
{
|
419 |
-
"loss/g/fm": loss_fm,
|
420 |
-
"loss/g/mel": loss_mel,
|
421 |
-
"loss/g/kl_ssl": kl_ssl,
|
422 |
-
"loss/g/kl": loss_kl,
|
423 |
-
}
|
424 |
-
)
|
425 |
-
|
426 |
-
# scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
|
427 |
-
# scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
|
428 |
-
# scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
|
429 |
-
image_dict = {
|
430 |
-
"slice/mel_org": utils.plot_spectrogram_to_numpy(
|
431 |
-
y_mel[0].data.cpu().numpy()
|
432 |
-
),
|
433 |
-
"slice/mel_gen": utils.plot_spectrogram_to_numpy(
|
434 |
-
y_hat_mel[0].data.cpu().numpy()
|
435 |
-
),
|
436 |
-
"all/mel": utils.plot_spectrogram_to_numpy(
|
437 |
-
mel[0].data.cpu().numpy()
|
438 |
-
),
|
439 |
-
"all/stats_ssl": utils.plot_spectrogram_to_numpy(
|
440 |
-
stats_ssl[0].data.cpu().numpy()
|
441 |
-
),
|
442 |
-
}
|
443 |
-
utils.summarize(
|
444 |
-
writer=writer,
|
445 |
-
global_step=global_step,
|
446 |
-
images=image_dict,
|
447 |
-
scalars=scalar_dict,
|
448 |
-
)
|
449 |
-
global_step += 1
|
450 |
-
if epoch % hps.train.save_every_epoch == 0 and rank == 0:
|
451 |
-
if hps.train.if_save_latest == 0:
|
452 |
-
utils.save_checkpoint(
|
453 |
-
net_g,
|
454 |
-
optim_g,
|
455 |
-
hps.train.learning_rate,
|
456 |
-
epoch,
|
457 |
-
os.path.join(
|
458 |
-
"%s/logs_s2" % hps.data.exp_dir, "G_{}.pth".format(global_step)
|
459 |
-
),
|
460 |
-
)
|
461 |
-
utils.save_checkpoint(
|
462 |
-
net_d,
|
463 |
-
optim_d,
|
464 |
-
hps.train.learning_rate,
|
465 |
-
epoch,
|
466 |
-
os.path.join(
|
467 |
-
"%s/logs_s2" % hps.data.exp_dir, "D_{}.pth".format(global_step)
|
468 |
-
),
|
469 |
-
)
|
470 |
-
else:
|
471 |
-
utils.save_checkpoint(
|
472 |
-
net_g,
|
473 |
-
optim_g,
|
474 |
-
hps.train.learning_rate,
|
475 |
-
epoch,
|
476 |
-
os.path.join(
|
477 |
-
"%s/logs_s2" % hps.data.exp_dir, "G_{}.pth".format(233333333333)
|
478 |
-
),
|
479 |
-
)
|
480 |
-
utils.save_checkpoint(
|
481 |
-
net_d,
|
482 |
-
optim_d,
|
483 |
-
hps.train.learning_rate,
|
484 |
-
epoch,
|
485 |
-
os.path.join(
|
486 |
-
"%s/logs_s2" % hps.data.exp_dir, "D_{}.pth".format(233333333333)
|
487 |
-
),
|
488 |
-
)
|
489 |
-
if rank == 0 and hps.train.if_save_every_weights == True:
|
490 |
-
if hasattr(net_g, "module"):
|
491 |
-
ckpt = net_g.module.state_dict()
|
492 |
-
else:
|
493 |
-
ckpt = net_g.state_dict()
|
494 |
-
logger.info(
|
495 |
-
"saving ckpt %s_e%s:%s"
|
496 |
-
% (
|
497 |
-
hps.name,
|
498 |
-
epoch,
|
499 |
-
savee(
|
500 |
-
ckpt,
|
501 |
-
hps.name + "_e%s_s%s" % (epoch, global_step),
|
502 |
-
epoch,
|
503 |
-
global_step,
|
504 |
-
hps,
|
505 |
-
),
|
506 |
-
)
|
507 |
-
)
|
508 |
-
|
509 |
-
if rank == 0:
|
510 |
-
logger.info("====> Epoch: {}".format(epoch))
|
511 |
-
|
512 |
-
|
513 |
-
def evaluate(hps, generator, eval_loader, writer_eval):
|
514 |
-
generator.eval()
|
515 |
-
image_dict = {}
|
516 |
-
audio_dict = {}
|
517 |
-
print("Evaluating ...")
|
518 |
-
with torch.no_grad():
|
519 |
-
for batch_idx, (
|
520 |
-
ssl,
|
521 |
-
ssl_lengths,
|
522 |
-
spec,
|
523 |
-
spec_lengths,
|
524 |
-
y,
|
525 |
-
y_lengths,
|
526 |
-
text,
|
527 |
-
text_lengths,
|
528 |
-
) in enumerate(eval_loader):
|
529 |
-
print(111)
|
530 |
-
if torch.cuda.is_available():
|
531 |
-
spec, spec_lengths = spec.cuda(), spec_lengths.cuda()
|
532 |
-
y, y_lengths = y.cuda(), y_lengths.cuda()
|
533 |
-
ssl = ssl.cuda()
|
534 |
-
text, text_lengths = text.cuda(), text_lengths.cuda()
|
535 |
-
else:
|
536 |
-
spec, spec_lengths = spec.to(device), spec_lengths.to(device)
|
537 |
-
y, y_lengths = y.to(device), y_lengths.to(device)
|
538 |
-
ssl = ssl.to(device)
|
539 |
-
text, text_lengths = text.to(device), text_lengths.to(device)
|
540 |
-
for test in [0, 1]:
|
541 |
-
y_hat, mask, *_ = generator.module.infer(
|
542 |
-
ssl, spec, spec_lengths, text, text_lengths, test=test
|
543 |
-
) if torch.cuda.is_available() else generator.infer(
|
544 |
-
ssl, spec, spec_lengths, text, text_lengths, test=test
|
545 |
-
)
|
546 |
-
y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length
|
547 |
-
|
548 |
-
mel = spec_to_mel_torch(
|
549 |
-
spec,
|
550 |
-
hps.data.filter_length,
|
551 |
-
hps.data.n_mel_channels,
|
552 |
-
hps.data.sampling_rate,
|
553 |
-
hps.data.mel_fmin,
|
554 |
-
hps.data.mel_fmax,
|
555 |
-
)
|
556 |
-
y_hat_mel = mel_spectrogram_torch(
|
557 |
-
y_hat.squeeze(1).float(),
|
558 |
-
hps.data.filter_length,
|
559 |
-
hps.data.n_mel_channels,
|
560 |
-
hps.data.sampling_rate,
|
561 |
-
hps.data.hop_length,
|
562 |
-
hps.data.win_length,
|
563 |
-
hps.data.mel_fmin,
|
564 |
-
hps.data.mel_fmax,
|
565 |
-
)
|
566 |
-
image_dict.update(
|
567 |
-
{
|
568 |
-
f"gen/mel_{batch_idx}_{test}": utils.plot_spectrogram_to_numpy(
|
569 |
-
y_hat_mel[0].cpu().numpy()
|
570 |
-
)
|
571 |
-
}
|
572 |
-
)
|
573 |
-
audio_dict.update(
|
574 |
-
{f"gen/audio_{batch_idx}_{test}": y_hat[0, :, : y_hat_lengths[0]]}
|
575 |
-
)
|
576 |
-
image_dict.update(
|
577 |
-
{
|
578 |
-
f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(
|
579 |
-
mel[0].cpu().numpy()
|
580 |
-
)
|
581 |
-
}
|
582 |
-
)
|
583 |
-
audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, : y_lengths[0]]})
|
584 |
-
|
585 |
-
# y_hat, mask, *_ = generator.module.infer(ssl, spec_lengths, speakers, y=None)
|
586 |
-
# audio_dict.update({
|
587 |
-
# f"gen/audio_{batch_idx}_style_pred": y_hat[0, :, :]
|
588 |
-
# })
|
589 |
-
|
590 |
-
utils.summarize(
|
591 |
-
writer=writer_eval,
|
592 |
-
global_step=global_step,
|
593 |
-
images=image_dict,
|
594 |
-
audios=audio_dict,
|
595 |
-
audio_sampling_rate=hps.data.sampling_rate,
|
596 |
-
)
|
597 |
-
generator.train()
|
598 |
-
|
599 |
-
|
600 |
-
if __name__ == "__main__":
|
601 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/__init__.py
DELETED
File without changes
|
tools/asr/config.py
DELETED
@@ -1,33 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
def check_fw_local_models():
|
4 |
-
'''
|
5 |
-
启动时检查本地是否有 Faster Whisper 模型.
|
6 |
-
'''
|
7 |
-
model_size_list = [
|
8 |
-
"tiny", "tiny.en",
|
9 |
-
"base", "base.en",
|
10 |
-
"small", "small.en",
|
11 |
-
"medium", "medium.en",
|
12 |
-
"large", "large-v1",
|
13 |
-
"large-v2", "large-v3"]
|
14 |
-
for i, size in enumerate(model_size_list):
|
15 |
-
if os.path.exists(f'tools/asr/models/faster-whisper-{size}'):
|
16 |
-
model_size_list[i] = size + '-local'
|
17 |
-
return model_size_list
|
18 |
-
|
19 |
-
asr_dict = {
|
20 |
-
"达摩 ASR (中文)": {
|
21 |
-
'lang': ['zh','yue'],
|
22 |
-
'size': ['large'],
|
23 |
-
'path': 'funasr_asr.py',
|
24 |
-
'precision': ['float32']
|
25 |
-
},
|
26 |
-
"Faster Whisper (多语种)": {
|
27 |
-
'lang': ['auto', 'zh', 'en', 'ja', 'ko', 'yue'],
|
28 |
-
'size': check_fw_local_models(),
|
29 |
-
'path': 'fasterwhisper_asr.py',
|
30 |
-
'precision': ['float32', 'float16', 'int8']
|
31 |
-
},
|
32 |
-
}
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/asr/fasterwhisper_asr.py
DELETED
@@ -1,114 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
import os
|
3 |
-
import traceback
|
4 |
-
|
5 |
-
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
|
6 |
-
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
7 |
-
|
8 |
-
import torch
|
9 |
-
from faster_whisper import WhisperModel
|
10 |
-
from tqdm import tqdm
|
11 |
-
|
12 |
-
from tools.asr.config import check_fw_local_models
|
13 |
-
|
14 |
-
language_code_list = [
|
15 |
-
"af", "am", "ar", "as", "az",
|
16 |
-
"ba", "be", "bg", "bn", "bo",
|
17 |
-
"br", "bs", "ca", "cs", "cy",
|
18 |
-
"da", "de", "el", "en", "es",
|
19 |
-
"et", "eu", "fa", "fi", "fo",
|
20 |
-
"fr", "gl", "gu", "ha", "haw",
|
21 |
-
"he", "hi", "hr", "ht", "hu",
|
22 |
-
"hy", "id", "is", "it", "ja",
|
23 |
-
"jw", "ka", "kk", "km", "kn",
|
24 |
-
"ko", "la", "lb", "ln", "lo",
|
25 |
-
"lt", "lv", "mg", "mi", "mk",
|
26 |
-
"ml", "mn", "mr", "ms", "mt",
|
27 |
-
"my", "ne", "nl", "nn", "no",
|
28 |
-
"oc", "pa", "pl", "ps", "pt",
|
29 |
-
"ro", "ru", "sa", "sd", "si",
|
30 |
-
"sk", "sl", "sn", "so", "sq",
|
31 |
-
"sr", "su", "sv", "sw", "ta",
|
32 |
-
"te", "tg", "th", "tk", "tl",
|
33 |
-
"tr", "tt", "uk", "ur", "uz",
|
34 |
-
"vi", "yi", "yo", "zh", "yue",
|
35 |
-
"auto"]
|
36 |
-
|
37 |
-
def execute_asr(input_folder, output_folder, model_size, language, precision):
|
38 |
-
if '-local' in model_size:
|
39 |
-
model_size = model_size[:-6]
|
40 |
-
model_path = f'tools/asr/models/faster-whisper-{model_size}'
|
41 |
-
else:
|
42 |
-
model_path = model_size
|
43 |
-
if language == 'auto':
|
44 |
-
language = None #不设置语种由模型自动输出概率最高的语种
|
45 |
-
print("loading faster whisper model:",model_size,model_path)
|
46 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
47 |
-
try:
|
48 |
-
model = WhisperModel(model_path, device=device, compute_type=precision)
|
49 |
-
except:
|
50 |
-
return print(traceback.format_exc())
|
51 |
-
|
52 |
-
input_file_names = os.listdir(input_folder)
|
53 |
-
input_file_names.sort()
|
54 |
-
|
55 |
-
output = []
|
56 |
-
output_file_name = os.path.basename(input_folder)
|
57 |
-
|
58 |
-
for file_name in tqdm(input_file_names):
|
59 |
-
try:
|
60 |
-
file_path = os.path.join(input_folder, file_name)
|
61 |
-
segments, info = model.transcribe(
|
62 |
-
audio = file_path,
|
63 |
-
beam_size = 5,
|
64 |
-
vad_filter = True,
|
65 |
-
vad_parameters = dict(min_silence_duration_ms=700),
|
66 |
-
language = language)
|
67 |
-
text = ''
|
68 |
-
|
69 |
-
if info.language == "zh":
|
70 |
-
print("检测为中文文本, 转 FunASR 处理")
|
71 |
-
if("only_asr"not in globals()):
|
72 |
-
from tools.asr.funasr_asr import \
|
73 |
-
only_asr # #如果用英文就不需要导入下载模型
|
74 |
-
text = only_asr(file_path)
|
75 |
-
|
76 |
-
if text == '':
|
77 |
-
for segment in segments:
|
78 |
-
text += segment.text
|
79 |
-
output.append(f"{file_path}|{output_file_name}|{info.language.upper()}|{text}")
|
80 |
-
except:
|
81 |
-
print(traceback.format_exc())
|
82 |
-
|
83 |
-
output_folder = output_folder or "output/asr_opt"
|
84 |
-
os.makedirs(output_folder, exist_ok=True)
|
85 |
-
output_file_path = os.path.abspath(f'{output_folder}/{output_file_name}.list')
|
86 |
-
|
87 |
-
with open(output_file_path, "w", encoding="utf-8") as f:
|
88 |
-
f.write("\n".join(output))
|
89 |
-
print(f"ASR 任务完成->标注文件路径: {output_file_path}\n")
|
90 |
-
return output_file_path
|
91 |
-
|
92 |
-
if __name__ == '__main__':
|
93 |
-
parser = argparse.ArgumentParser()
|
94 |
-
parser.add_argument("-i", "--input_folder", type=str, required=True,
|
95 |
-
help="Path to the folder containing WAV files.")
|
96 |
-
parser.add_argument("-o", "--output_folder", type=str, required=True,
|
97 |
-
help="Output folder to store transcriptions.")
|
98 |
-
parser.add_argument("-s", "--model_size", type=str, default='large-v3',
|
99 |
-
choices=check_fw_local_models(),
|
100 |
-
help="Model Size of Faster Whisper")
|
101 |
-
parser.add_argument("-l", "--language", type=str, default='ja',
|
102 |
-
choices=language_code_list,
|
103 |
-
help="Language of the audio files.")
|
104 |
-
parser.add_argument("-p", "--precision", type=str, default='float16', choices=['float16','float32','int8'],
|
105 |
-
help="fp16, int8 or fp32")
|
106 |
-
|
107 |
-
cmd = parser.parse_args()
|
108 |
-
output_file_path = execute_asr(
|
109 |
-
input_folder = cmd.input_folder,
|
110 |
-
output_folder = cmd.output_folder,
|
111 |
-
model_size = cmd.model_size,
|
112 |
-
language = cmd.language,
|
113 |
-
precision = cmd.precision,
|
114 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/asr/funasr_asr.py
DELETED
@@ -1,91 +0,0 @@
|
|
1 |
-
# -*- coding:utf-8 -*-
|
2 |
-
|
3 |
-
import argparse
|
4 |
-
import os
|
5 |
-
import traceback
|
6 |
-
from tqdm import tqdm
|
7 |
-
# from funasr.utils import version_checker
|
8 |
-
# version_checker.check_for_update = lambda: None
|
9 |
-
from funasr import AutoModel
|
10 |
-
|
11 |
-
|
12 |
-
def only_asr(input_file):
|
13 |
-
try:
|
14 |
-
text = model.generate(input=input_file)[0]["text"]
|
15 |
-
except:
|
16 |
-
text = ''
|
17 |
-
print(traceback.format_exc())
|
18 |
-
return text
|
19 |
-
|
20 |
-
def execute_asr(input_folder, output_folder, model_size, language):
|
21 |
-
input_file_names = os.listdir(input_folder)
|
22 |
-
input_file_names.sort()
|
23 |
-
|
24 |
-
output = []
|
25 |
-
output_file_name = os.path.basename(input_folder)
|
26 |
-
|
27 |
-
for file_name in tqdm(input_file_names):
|
28 |
-
try:
|
29 |
-
print(file_name)
|
30 |
-
file_path = os.path.join(input_folder, file_name)
|
31 |
-
text = model.generate(input=file_path)[0]["text"]
|
32 |
-
output.append(f"{file_path}|{output_file_name}|{language.upper()}|{text}")
|
33 |
-
except:
|
34 |
-
print(traceback.format_exc())
|
35 |
-
|
36 |
-
output_folder = output_folder or "output/asr_opt"
|
37 |
-
os.makedirs(output_folder, exist_ok=True)
|
38 |
-
output_file_path = os.path.abspath(f'{output_folder}/{output_file_name}.list')
|
39 |
-
|
40 |
-
with open(output_file_path, "w", encoding="utf-8") as f:
|
41 |
-
f.write("\n".join(output))
|
42 |
-
print(f"ASR 任务完成->标注文件路径: {output_file_path}\n")
|
43 |
-
return output_file_path
|
44 |
-
|
45 |
-
|
46 |
-
parser = argparse.ArgumentParser()
|
47 |
-
parser.add_argument("-i", "--input_folder", type=str, required=True,
|
48 |
-
help="Path to the folder containing WAV files.")
|
49 |
-
parser.add_argument("-o", "--output_folder", type=str, required=True,
|
50 |
-
help="Output folder to store transcriptions.")
|
51 |
-
parser.add_argument("-s", "--model_size", type=str, default='large',
|
52 |
-
help="Model Size of FunASR is Large")
|
53 |
-
parser.add_argument("-l", "--language", type=str, default='zh', choices=['zh','yue','auto'],
|
54 |
-
help="Language of the audio files.")
|
55 |
-
parser.add_argument("-p", "--precision", type=str, default='float16', choices=['float16','float32'],
|
56 |
-
help="fp16 or fp32")#还没接入
|
57 |
-
|
58 |
-
cmd = parser.parse_args()
|
59 |
-
|
60 |
-
path_vad = 'tools/asr/models/speech_fsmn_vad_zh-cn-16k-common-pytorch'
|
61 |
-
path_punc = 'tools/asr/models/punc_ct-transformer_zh-cn-common-vocab272727-pytorch'
|
62 |
-
path_vad = path_vad if os.path.exists(path_vad) else "iic/speech_fsmn_vad_zh-cn-16k-common-pytorch"
|
63 |
-
path_punc = path_punc if os.path.exists(path_punc) else "iic/punc_ct-transformer_zh-cn-common-vocab272727-pytorch"
|
64 |
-
vad_model_revision=punc_model_revision="v2.0.4"
|
65 |
-
|
66 |
-
if(cmd.language=="zh"):
|
67 |
-
path_asr = 'tools/asr/models/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch'
|
68 |
-
path_asr = path_asr if os.path.exists(path_asr) else "iic/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch"
|
69 |
-
model_revision="v2.0.4"
|
70 |
-
else:
|
71 |
-
path_asr = 'tools/asr/models/speech_UniASR_asr_2pass-cantonese-CHS-16k-common-vocab1468-tensorflow1-online'
|
72 |
-
path_asr = path_asr if os.path.exists(path_asr) else "iic/speech_UniASR_asr_2pass-cantonese-CHS-16k-common-vocab1468-tensorflow1-online"
|
73 |
-
model_revision="master"
|
74 |
-
path_vad=path_punc=vad_model_revision=punc_model_revision=None###友情提示:粤语带VAD识别可能会有少量shape不对报错的,但是不带VAD可以.不带vad只能分阶段单独加标点。不过标点模型对粤语效果真的不行…
|
75 |
-
|
76 |
-
model = AutoModel(
|
77 |
-
model=path_asr,
|
78 |
-
model_revision=model_revision,
|
79 |
-
vad_model=path_vad,
|
80 |
-
vad_model_revision=vad_model_revision,
|
81 |
-
punc_model=path_punc,
|
82 |
-
punc_model_revision=punc_model_revision,
|
83 |
-
)
|
84 |
-
|
85 |
-
if __name__ == '__main__':
|
86 |
-
execute_asr(
|
87 |
-
input_folder = cmd.input_folder,
|
88 |
-
output_folder = cmd.output_folder,
|
89 |
-
model_size = cmd.model_size,
|
90 |
-
language = cmd.language,
|
91 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/asr/models/.gitignore
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
*
|
2 |
-
!.gitignore
|
|
|
|
|
|
tools/cmd-denoise.py
DELETED
@@ -1,33 +0,0 @@
|
|
1 |
-
import os,argparse
|
2 |
-
import traceback
|
3 |
-
|
4 |
-
from modelscope.pipelines import pipeline
|
5 |
-
from modelscope.utils.constant import Tasks
|
6 |
-
from tqdm import tqdm
|
7 |
-
|
8 |
-
path_denoise = 'tools/denoise-model/speech_frcrn_ans_cirm_16k'
|
9 |
-
path_denoise = path_denoise if os.path.exists(path_denoise) else "damo/speech_frcrn_ans_cirm_16k"
|
10 |
-
ans = pipeline(Tasks.acoustic_noise_suppression,model=path_denoise)
|
11 |
-
def execute_denoise(input_folder,output_folder):
|
12 |
-
os.makedirs(output_folder,exist_ok=True)
|
13 |
-
# print(input_folder)
|
14 |
-
# print(list(os.listdir(input_folder).sort()))
|
15 |
-
for name in tqdm(os.listdir(input_folder)):
|
16 |
-
try:
|
17 |
-
ans("%s/%s"%(input_folder,name),output_path='%s/%s'%(output_folder,name))
|
18 |
-
except:
|
19 |
-
traceback.print_exc()
|
20 |
-
|
21 |
-
if __name__ == '__main__':
|
22 |
-
parser = argparse.ArgumentParser()
|
23 |
-
parser.add_argument("-i", "--input_folder", type=str, required=True,
|
24 |
-
help="Path to the folder containing WAV files.")
|
25 |
-
parser.add_argument("-o", "--output_folder", type=str, required=True,
|
26 |
-
help="Output folder to store transcriptions.")
|
27 |
-
parser.add_argument("-p", "--precision", type=str, default='float16', choices=['float16','float32'],
|
28 |
-
help="fp16 or fp32")#还没接入
|
29 |
-
cmd = parser.parse_args()
|
30 |
-
execute_denoise(
|
31 |
-
input_folder = cmd.input_folder,
|
32 |
-
output_folder = cmd.output_folder,
|
33 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/denoise-model/.gitignore
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
*
|
2 |
-
!.gitignore
|
|
|
|
|
|
tools/slice_audio.py
DELETED
@@ -1,48 +0,0 @@
|
|
1 |
-
import os,sys,numpy as np
|
2 |
-
import traceback
|
3 |
-
from scipy.io import wavfile
|
4 |
-
# parent_directory = os.path.dirname(os.path.abspath(__file__))
|
5 |
-
# sys.path.append(parent_directory)
|
6 |
-
from tools.my_utils import load_audio
|
7 |
-
from slicer2 import Slicer
|
8 |
-
|
9 |
-
def slice(inp,opt_root,threshold,min_length,min_interval,hop_size,max_sil_kept,_max,alpha,i_part,all_part):
|
10 |
-
os.makedirs(opt_root,exist_ok=True)
|
11 |
-
if os.path.isfile(inp):
|
12 |
-
input=[inp]
|
13 |
-
elif os.path.isdir(inp):
|
14 |
-
input=[os.path.join(inp, name) for name in sorted(list(os.listdir(inp)))]
|
15 |
-
else:
|
16 |
-
return "输入路径存在但既不是文件也不是文件夹"
|
17 |
-
slicer = Slicer(
|
18 |
-
sr=32000, # 长音频采样率
|
19 |
-
threshold= int(threshold), # 音量小于这个值视作静音的备选切割点
|
20 |
-
min_length= int(min_length), # 每段最小多长,如果第一段太短一直和后面段连起来直到超过这个值
|
21 |
-
min_interval= int(min_interval), # 最短切割间隔
|
22 |
-
hop_size= int(hop_size), # 怎么算音量曲线,越小精度越大计算量越高(不是精度越大效果越好)
|
23 |
-
max_sil_kept= int(max_sil_kept), # 切完后静音最多留多长
|
24 |
-
)
|
25 |
-
_max=float(_max)
|
26 |
-
alpha=float(alpha)
|
27 |
-
for inp_path in input[int(i_part)::int(all_part)]:
|
28 |
-
# print(inp_path)
|
29 |
-
try:
|
30 |
-
name = os.path.basename(inp_path)
|
31 |
-
audio = load_audio(inp_path, 32000)
|
32 |
-
# print(audio.shape)
|
33 |
-
for chunk, start, end in slicer.slice(audio): # start和end是帧数
|
34 |
-
tmp_max = np.abs(chunk).max()
|
35 |
-
if(tmp_max>1):chunk/=tmp_max
|
36 |
-
chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
|
37 |
-
wavfile.write(
|
38 |
-
"%s/%s_%010d_%010d.wav" % (opt_root, name, start, end),
|
39 |
-
32000,
|
40 |
-
# chunk.astype(np.float32),
|
41 |
-
(chunk * 32767).astype(np.int16),
|
42 |
-
)
|
43 |
-
except:
|
44 |
-
print(inp_path,"->fail->",traceback.format_exc())
|
45 |
-
return "执行完毕,请检查输出文件"
|
46 |
-
|
47 |
-
print(slice(*sys.argv[1:]))
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/slicer2.py
DELETED
@@ -1,261 +0,0 @@
|
|
1 |
-
import numpy as np
|
2 |
-
|
3 |
-
|
4 |
-
# This function is obtained from librosa.
|
5 |
-
def get_rms(
|
6 |
-
y,
|
7 |
-
frame_length=2048,
|
8 |
-
hop_length=512,
|
9 |
-
pad_mode="constant",
|
10 |
-
):
|
11 |
-
padding = (int(frame_length // 2), int(frame_length // 2))
|
12 |
-
y = np.pad(y, padding, mode=pad_mode)
|
13 |
-
|
14 |
-
axis = -1
|
15 |
-
# put our new within-frame axis at the end for now
|
16 |
-
out_strides = y.strides + tuple([y.strides[axis]])
|
17 |
-
# Reduce the shape on the framing axis
|
18 |
-
x_shape_trimmed = list(y.shape)
|
19 |
-
x_shape_trimmed[axis] -= frame_length - 1
|
20 |
-
out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
|
21 |
-
xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
|
22 |
-
if axis < 0:
|
23 |
-
target_axis = axis - 1
|
24 |
-
else:
|
25 |
-
target_axis = axis + 1
|
26 |
-
xw = np.moveaxis(xw, -1, target_axis)
|
27 |
-
# Downsample along the target axis
|
28 |
-
slices = [slice(None)] * xw.ndim
|
29 |
-
slices[axis] = slice(0, None, hop_length)
|
30 |
-
x = xw[tuple(slices)]
|
31 |
-
|
32 |
-
# Calculate power
|
33 |
-
power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
|
34 |
-
|
35 |
-
return np.sqrt(power)
|
36 |
-
|
37 |
-
|
38 |
-
class Slicer:
|
39 |
-
def __init__(
|
40 |
-
self,
|
41 |
-
sr: int,
|
42 |
-
threshold: float = -40.0,
|
43 |
-
min_length: int = 5000,
|
44 |
-
min_interval: int = 300,
|
45 |
-
hop_size: int = 20,
|
46 |
-
max_sil_kept: int = 5000,
|
47 |
-
):
|
48 |
-
if not min_length >= min_interval >= hop_size:
|
49 |
-
raise ValueError(
|
50 |
-
"The following condition must be satisfied: min_length >= min_interval >= hop_size"
|
51 |
-
)
|
52 |
-
if not max_sil_kept >= hop_size:
|
53 |
-
raise ValueError(
|
54 |
-
"The following condition must be satisfied: max_sil_kept >= hop_size"
|
55 |
-
)
|
56 |
-
min_interval = sr * min_interval / 1000
|
57 |
-
self.threshold = 10 ** (threshold / 20.0)
|
58 |
-
self.hop_size = round(sr * hop_size / 1000)
|
59 |
-
self.win_size = min(round(min_interval), 4 * self.hop_size)
|
60 |
-
self.min_length = round(sr * min_length / 1000 / self.hop_size)
|
61 |
-
self.min_interval = round(min_interval / self.hop_size)
|
62 |
-
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
|
63 |
-
|
64 |
-
def _apply_slice(self, waveform, begin, end):
|
65 |
-
if len(waveform.shape) > 1:
|
66 |
-
return waveform[
|
67 |
-
:, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)
|
68 |
-
]
|
69 |
-
else:
|
70 |
-
return waveform[
|
71 |
-
begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)
|
72 |
-
]
|
73 |
-
|
74 |
-
# @timeit
|
75 |
-
def slice(self, waveform):
|
76 |
-
if len(waveform.shape) > 1:
|
77 |
-
samples = waveform.mean(axis=0)
|
78 |
-
else:
|
79 |
-
samples = waveform
|
80 |
-
if samples.shape[0] <= self.min_length:
|
81 |
-
return [waveform]
|
82 |
-
rms_list = get_rms(
|
83 |
-
y=samples, frame_length=self.win_size, hop_length=self.hop_size
|
84 |
-
).squeeze(0)
|
85 |
-
sil_tags = []
|
86 |
-
silence_start = None
|
87 |
-
clip_start = 0
|
88 |
-
for i, rms in enumerate(rms_list):
|
89 |
-
# Keep looping while frame is silent.
|
90 |
-
if rms < self.threshold:
|
91 |
-
# Record start of silent frames.
|
92 |
-
if silence_start is None:
|
93 |
-
silence_start = i
|
94 |
-
continue
|
95 |
-
# Keep looping while frame is not silent and silence start has not been recorded.
|
96 |
-
if silence_start is None:
|
97 |
-
continue
|
98 |
-
# Clear recorded silence start if interval is not enough or clip is too short
|
99 |
-
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
|
100 |
-
need_slice_middle = (
|
101 |
-
i - silence_start >= self.min_interval
|
102 |
-
and i - clip_start >= self.min_length
|
103 |
-
)
|
104 |
-
if not is_leading_silence and not need_slice_middle:
|
105 |
-
silence_start = None
|
106 |
-
continue
|
107 |
-
# Need slicing. Record the range of silent frames to be removed.
|
108 |
-
if i - silence_start <= self.max_sil_kept:
|
109 |
-
pos = rms_list[silence_start : i + 1].argmin() + silence_start
|
110 |
-
if silence_start == 0:
|
111 |
-
sil_tags.append((0, pos))
|
112 |
-
else:
|
113 |
-
sil_tags.append((pos, pos))
|
114 |
-
clip_start = pos
|
115 |
-
elif i - silence_start <= self.max_sil_kept * 2:
|
116 |
-
pos = rms_list[
|
117 |
-
i - self.max_sil_kept : silence_start + self.max_sil_kept + 1
|
118 |
-
].argmin()
|
119 |
-
pos += i - self.max_sil_kept
|
120 |
-
pos_l = (
|
121 |
-
rms_list[
|
122 |
-
silence_start : silence_start + self.max_sil_kept + 1
|
123 |
-
].argmin()
|
124 |
-
+ silence_start
|
125 |
-
)
|
126 |
-
pos_r = (
|
127 |
-
rms_list[i - self.max_sil_kept : i + 1].argmin()
|
128 |
-
+ i
|
129 |
-
- self.max_sil_kept
|
130 |
-
)
|
131 |
-
if silence_start == 0:
|
132 |
-
sil_tags.append((0, pos_r))
|
133 |
-
clip_start = pos_r
|
134 |
-
else:
|
135 |
-
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
|
136 |
-
clip_start = max(pos_r, pos)
|
137 |
-
else:
|
138 |
-
pos_l = (
|
139 |
-
rms_list[
|
140 |
-
silence_start : silence_start + self.max_sil_kept + 1
|
141 |
-
].argmin()
|
142 |
-
+ silence_start
|
143 |
-
)
|
144 |
-
pos_r = (
|
145 |
-
rms_list[i - self.max_sil_kept : i + 1].argmin()
|
146 |
-
+ i
|
147 |
-
- self.max_sil_kept
|
148 |
-
)
|
149 |
-
if silence_start == 0:
|
150 |
-
sil_tags.append((0, pos_r))
|
151 |
-
else:
|
152 |
-
sil_tags.append((pos_l, pos_r))
|
153 |
-
clip_start = pos_r
|
154 |
-
silence_start = None
|
155 |
-
# Deal with trailing silence.
|
156 |
-
total_frames = rms_list.shape[0]
|
157 |
-
if (
|
158 |
-
silence_start is not None
|
159 |
-
and total_frames - silence_start >= self.min_interval
|
160 |
-
):
|
161 |
-
silence_end = min(total_frames, silence_start + self.max_sil_kept)
|
162 |
-
pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
|
163 |
-
sil_tags.append((pos, total_frames + 1))
|
164 |
-
# Apply and return slices.
|
165 |
-
####音频+起始时间+终止时间
|
166 |
-
if len(sil_tags) == 0:
|
167 |
-
return [[waveform,0,int(total_frames*self.hop_size)]]
|
168 |
-
else:
|
169 |
-
chunks = []
|
170 |
-
if sil_tags[0][0] > 0:
|
171 |
-
chunks.append([self._apply_slice(waveform, 0, sil_tags[0][0]),0,int(sil_tags[0][0]*self.hop_size)])
|
172 |
-
for i in range(len(sil_tags) - 1):
|
173 |
-
chunks.append(
|
174 |
-
[self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]),int(sil_tags[i][1]*self.hop_size),int(sil_tags[i + 1][0]*self.hop_size)]
|
175 |
-
)
|
176 |
-
if sil_tags[-1][1] < total_frames:
|
177 |
-
chunks.append(
|
178 |
-
[self._apply_slice(waveform, sil_tags[-1][1], total_frames),int(sil_tags[-1][1]*self.hop_size),int(total_frames*self.hop_size)]
|
179 |
-
)
|
180 |
-
return chunks
|
181 |
-
|
182 |
-
|
183 |
-
def main():
|
184 |
-
import os.path
|
185 |
-
from argparse import ArgumentParser
|
186 |
-
|
187 |
-
import librosa
|
188 |
-
import soundfile
|
189 |
-
|
190 |
-
parser = ArgumentParser()
|
191 |
-
parser.add_argument("audio", type=str, help="The audio to be sliced")
|
192 |
-
parser.add_argument(
|
193 |
-
"--out", type=str, help="Output directory of the sliced audio clips"
|
194 |
-
)
|
195 |
-
parser.add_argument(
|
196 |
-
"--db_thresh",
|
197 |
-
type=float,
|
198 |
-
required=False,
|
199 |
-
default=-40,
|
200 |
-
help="The dB threshold for silence detection",
|
201 |
-
)
|
202 |
-
parser.add_argument(
|
203 |
-
"--min_length",
|
204 |
-
type=int,
|
205 |
-
required=False,
|
206 |
-
default=5000,
|
207 |
-
help="The minimum milliseconds required for each sliced audio clip",
|
208 |
-
)
|
209 |
-
parser.add_argument(
|
210 |
-
"--min_interval",
|
211 |
-
type=int,
|
212 |
-
required=False,
|
213 |
-
default=300,
|
214 |
-
help="The minimum milliseconds for a silence part to be sliced",
|
215 |
-
)
|
216 |
-
parser.add_argument(
|
217 |
-
"--hop_size",
|
218 |
-
type=int,
|
219 |
-
required=False,
|
220 |
-
default=10,
|
221 |
-
help="Frame length in milliseconds",
|
222 |
-
)
|
223 |
-
parser.add_argument(
|
224 |
-
"--max_sil_kept",
|
225 |
-
type=int,
|
226 |
-
required=False,
|
227 |
-
default=500,
|
228 |
-
help="The maximum silence length kept around the sliced clip, presented in milliseconds",
|
229 |
-
)
|
230 |
-
args = parser.parse_args()
|
231 |
-
out = args.out
|
232 |
-
if out is None:
|
233 |
-
out = os.path.dirname(os.path.abspath(args.audio))
|
234 |
-
audio, sr = librosa.load(args.audio, sr=None, mono=False)
|
235 |
-
slicer = Slicer(
|
236 |
-
sr=sr,
|
237 |
-
threshold=args.db_thresh,
|
238 |
-
min_length=args.min_length,
|
239 |
-
min_interval=args.min_interval,
|
240 |
-
hop_size=args.hop_size,
|
241 |
-
max_sil_kept=args.max_sil_kept,
|
242 |
-
)
|
243 |
-
chunks = slicer.slice(audio)
|
244 |
-
if not os.path.exists(out):
|
245 |
-
os.makedirs(out)
|
246 |
-
for i, chunk in enumerate(chunks):
|
247 |
-
if len(chunk.shape) > 1:
|
248 |
-
chunk = chunk.T
|
249 |
-
soundfile.write(
|
250 |
-
os.path.join(
|
251 |
-
out,
|
252 |
-
f"%s_%d.wav"
|
253 |
-
% (os.path.basename(args.audio).rsplit(".", maxsplit=1)[0], i),
|
254 |
-
),
|
255 |
-
chunk,
|
256 |
-
sr,
|
257 |
-
)
|
258 |
-
|
259 |
-
|
260 |
-
if __name__ == "__main__":
|
261 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/subfix_webui.py
DELETED
@@ -1,498 +0,0 @@
|
|
1 |
-
import argparse,os
|
2 |
-
import copy
|
3 |
-
import json
|
4 |
-
import os
|
5 |
-
import uuid
|
6 |
-
|
7 |
-
import librosa
|
8 |
-
import gradio as gr
|
9 |
-
import numpy as np
|
10 |
-
import soundfile
|
11 |
-
|
12 |
-
g_json_key_text = ""
|
13 |
-
g_json_key_path = ""
|
14 |
-
g_load_file = ""
|
15 |
-
g_load_format = ""
|
16 |
-
|
17 |
-
g_max_json_index = 0
|
18 |
-
g_index = 0
|
19 |
-
g_batch = 10
|
20 |
-
g_text_list = []
|
21 |
-
g_audio_list = []
|
22 |
-
g_checkbox_list = []
|
23 |
-
g_data_json = []
|
24 |
-
|
25 |
-
|
26 |
-
def reload_data(index, batch):
|
27 |
-
global g_index
|
28 |
-
g_index = index
|
29 |
-
global g_batch
|
30 |
-
g_batch = batch
|
31 |
-
datas = g_data_json[index:index+batch]
|
32 |
-
output = []
|
33 |
-
for d in datas:
|
34 |
-
output.append(
|
35 |
-
{
|
36 |
-
g_json_key_text: d[g_json_key_text],
|
37 |
-
g_json_key_path: d[g_json_key_path]
|
38 |
-
}
|
39 |
-
)
|
40 |
-
return output
|
41 |
-
|
42 |
-
|
43 |
-
def b_change_index(index, batch):
|
44 |
-
global g_index, g_batch
|
45 |
-
g_index, g_batch = index, batch
|
46 |
-
datas = reload_data(index, batch)
|
47 |
-
output = []
|
48 |
-
for i , _ in enumerate(datas):
|
49 |
-
output.append(
|
50 |
-
# gr.Textbox(
|
51 |
-
# label=f"Text {i+index}",
|
52 |
-
# value=_[g_json_key_text]#text
|
53 |
-
# )
|
54 |
-
{
|
55 |
-
"__type__":"update",
|
56 |
-
"label":f"Text {i+index}",
|
57 |
-
"value":_[g_json_key_text]
|
58 |
-
}
|
59 |
-
)
|
60 |
-
for _ in range(g_batch - len(datas)):
|
61 |
-
output.append(
|
62 |
-
# gr.Textbox(
|
63 |
-
# label=f"Text",
|
64 |
-
# value=""
|
65 |
-
# )
|
66 |
-
{
|
67 |
-
"__type__": "update",
|
68 |
-
"label": f"Text",
|
69 |
-
"value": ""
|
70 |
-
}
|
71 |
-
)
|
72 |
-
for _ in datas:
|
73 |
-
output.append(_[g_json_key_path])
|
74 |
-
for _ in range(g_batch - len(datas)):
|
75 |
-
output.append(None)
|
76 |
-
for _ in range(g_batch):
|
77 |
-
output.append(False)
|
78 |
-
return output
|
79 |
-
|
80 |
-
|
81 |
-
def b_next_index(index, batch):
|
82 |
-
b_save_file()
|
83 |
-
if (index + batch) <= g_max_json_index:
|
84 |
-
return index + batch , *b_change_index(index + batch, batch)
|
85 |
-
else:
|
86 |
-
return index, *b_change_index(index, batch)
|
87 |
-
|
88 |
-
|
89 |
-
def b_previous_index(index, batch):
|
90 |
-
b_save_file()
|
91 |
-
if (index - batch) >= 0:
|
92 |
-
return index - batch , *b_change_index(index - batch, batch)
|
93 |
-
else:
|
94 |
-
return 0, *b_change_index(0, batch)
|
95 |
-
|
96 |
-
|
97 |
-
def b_submit_change(*text_list):
|
98 |
-
global g_data_json
|
99 |
-
change = False
|
100 |
-
for i, new_text in enumerate(text_list):
|
101 |
-
if g_index + i <= g_max_json_index:
|
102 |
-
new_text = new_text.strip()+' '
|
103 |
-
if (g_data_json[g_index + i][g_json_key_text] != new_text):
|
104 |
-
g_data_json[g_index + i][g_json_key_text] = new_text
|
105 |
-
change = True
|
106 |
-
if change:
|
107 |
-
b_save_file()
|
108 |
-
return g_index, *b_change_index(g_index, g_batch)
|
109 |
-
|
110 |
-
|
111 |
-
def b_delete_audio(*checkbox_list):
|
112 |
-
global g_data_json, g_index, g_max_json_index
|
113 |
-
b_save_file()
|
114 |
-
change = False
|
115 |
-
for i, checkbox in reversed(list(enumerate(checkbox_list))):
|
116 |
-
if g_index + i < len(g_data_json):
|
117 |
-
if (checkbox == True):
|
118 |
-
g_data_json.pop(g_index + i)
|
119 |
-
change = True
|
120 |
-
|
121 |
-
g_max_json_index = len(g_data_json)-1
|
122 |
-
if g_index > g_max_json_index:
|
123 |
-
g_index = g_max_json_index
|
124 |
-
g_index = g_index if g_index >= 0 else 0
|
125 |
-
if change:
|
126 |
-
b_save_file()
|
127 |
-
# return gr.Slider(value=g_index, maximum=(g_max_json_index if g_max_json_index>=0 else 0)), *b_change_index(g_index, g_batch)
|
128 |
-
return {"value":g_index,"__type__":"update","maximum":(g_max_json_index if g_max_json_index>=0 else 0)},*b_change_index(g_index, g_batch)
|
129 |
-
|
130 |
-
|
131 |
-
def b_invert_selection(*checkbox_list):
|
132 |
-
new_list = [not item if item is True else True for item in checkbox_list]
|
133 |
-
return new_list
|
134 |
-
|
135 |
-
|
136 |
-
def get_next_path(filename):
|
137 |
-
base_dir = os.path.dirname(filename)
|
138 |
-
base_name = os.path.splitext(os.path.basename(filename))[0]
|
139 |
-
for i in range(100):
|
140 |
-
new_path = os.path.join(base_dir, f"{base_name}_{str(i).zfill(2)}.wav")
|
141 |
-
if not os.path.exists(new_path) :
|
142 |
-
return new_path
|
143 |
-
return os.path.join(base_dir, f'{str(uuid.uuid4())}.wav')
|
144 |
-
|
145 |
-
|
146 |
-
def b_audio_split(audio_breakpoint, *checkbox_list):
|
147 |
-
global g_data_json , g_max_json_index
|
148 |
-
checked_index = []
|
149 |
-
for i, checkbox in enumerate(checkbox_list):
|
150 |
-
if (checkbox == True and g_index+i < len(g_data_json)):
|
151 |
-
checked_index.append(g_index + i)
|
152 |
-
if len(checked_index) == 1 :
|
153 |
-
index = checked_index[0]
|
154 |
-
audio_json = copy.deepcopy(g_data_json[index])
|
155 |
-
path = audio_json[g_json_key_path]
|
156 |
-
data, sample_rate = librosa.load(path, sr=None, mono=True)
|
157 |
-
audio_maxframe = len(data)
|
158 |
-
break_frame = int(audio_breakpoint * sample_rate)
|
159 |
-
|
160 |
-
if (break_frame >= 1 and break_frame < audio_maxframe):
|
161 |
-
audio_first = data[0:break_frame]
|
162 |
-
audio_second = data[break_frame:]
|
163 |
-
nextpath = get_next_path(path)
|
164 |
-
soundfile.write(nextpath, audio_second, sample_rate)
|
165 |
-
soundfile.write(path, audio_first, sample_rate)
|
166 |
-
g_data_json.insert(index + 1, audio_json)
|
167 |
-
g_data_json[index + 1][g_json_key_path] = nextpath
|
168 |
-
b_save_file()
|
169 |
-
|
170 |
-
g_max_json_index = len(g_data_json) - 1
|
171 |
-
# return gr.Slider(value=g_index, maximum=g_max_json_index), *b_change_index(g_index, g_batch)
|
172 |
-
return {"value":g_index,"maximum":g_max_json_index,"__type__":"update"}, *b_change_index(g_index, g_batch)
|
173 |
-
|
174 |
-
def b_merge_audio(interval_r, *checkbox_list):
|
175 |
-
global g_data_json , g_max_json_index
|
176 |
-
b_save_file()
|
177 |
-
checked_index = []
|
178 |
-
audios_path = []
|
179 |
-
audios_text = []
|
180 |
-
for i, checkbox in enumerate(checkbox_list):
|
181 |
-
if (checkbox == True and g_index+i < len(g_data_json)):
|
182 |
-
checked_index.append(g_index + i)
|
183 |
-
|
184 |
-
if (len(checked_index)>1):
|
185 |
-
for i in checked_index:
|
186 |
-
audios_path.append(g_data_json[i][g_json_key_path])
|
187 |
-
audios_text.append(g_data_json[i][g_json_key_text])
|
188 |
-
for i in reversed(checked_index[1:]):
|
189 |
-
g_data_json.pop(i)
|
190 |
-
|
191 |
-
base_index = checked_index[0]
|
192 |
-
base_path = audios_path[0]
|
193 |
-
g_data_json[base_index][g_json_key_text] = "".join(audios_text)
|
194 |
-
|
195 |
-
audio_list = []
|
196 |
-
l_sample_rate = None
|
197 |
-
for i, path in enumerate(audios_path):
|
198 |
-
data, sample_rate = librosa.load(path, sr=l_sample_rate, mono=True)
|
199 |
-
l_sample_rate = sample_rate
|
200 |
-
if (i > 0):
|
201 |
-
silence = np.zeros(int(l_sample_rate * interval_r))
|
202 |
-
audio_list.append(silence)
|
203 |
-
|
204 |
-
audio_list.append(data)
|
205 |
-
|
206 |
-
audio_concat = np.concatenate(audio_list)
|
207 |
-
|
208 |
-
soundfile.write(base_path, audio_concat, l_sample_rate)
|
209 |
-
|
210 |
-
b_save_file()
|
211 |
-
|
212 |
-
g_max_json_index = len(g_data_json) - 1
|
213 |
-
|
214 |
-
# return gr.Slider(value=g_index, maximum=g_max_json_index), *b_change_index(g_index, g_batch)
|
215 |
-
return {"value":g_index,"maximum":g_max_json_index,"__type__":"update"}, *b_change_index(g_index, g_batch)
|
216 |
-
|
217 |
-
|
218 |
-
def b_save_json():
|
219 |
-
with open(g_load_file,'w', encoding="utf-8") as file:
|
220 |
-
for data in g_data_json:
|
221 |
-
file.write(f'{json.dumps(data, ensure_ascii = False)}\n')
|
222 |
-
|
223 |
-
|
224 |
-
def b_save_list():
|
225 |
-
with open(g_load_file,'w', encoding="utf-8") as file:
|
226 |
-
for data in g_data_json:
|
227 |
-
wav_path = data["wav_path"]
|
228 |
-
speaker_name = data["speaker_name"]
|
229 |
-
language = data["language"]
|
230 |
-
text = data["text"]
|
231 |
-
file.write(f"{wav_path}|{speaker_name}|{language}|{text}".strip()+'\n')
|
232 |
-
|
233 |
-
|
234 |
-
def b_load_json():
|
235 |
-
global g_data_json, g_max_json_index
|
236 |
-
with open(g_load_file, 'r', encoding="utf-8") as file:
|
237 |
-
g_data_json = file.readlines()
|
238 |
-
g_data_json = [json.loads(line) for line in g_data_json]
|
239 |
-
g_max_json_index = len(g_data_json) - 1
|
240 |
-
|
241 |
-
|
242 |
-
def b_load_list():
|
243 |
-
global g_data_json, g_max_json_index
|
244 |
-
with open(g_load_file, 'r', encoding="utf-8") as source:
|
245 |
-
data_list = source.readlines()
|
246 |
-
for _ in data_list:
|
247 |
-
data = _.split('|')
|
248 |
-
if (len(data) == 4):
|
249 |
-
wav_path, speaker_name, language, text = data
|
250 |
-
g_data_json.append(
|
251 |
-
{
|
252 |
-
'wav_path':wav_path,
|
253 |
-
'speaker_name':speaker_name,
|
254 |
-
'language':language,
|
255 |
-
'text':text.strip()
|
256 |
-
}
|
257 |
-
)
|
258 |
-
else:
|
259 |
-
print("error line:", data)
|
260 |
-
g_max_json_index = len(g_data_json) - 1
|
261 |
-
|
262 |
-
|
263 |
-
def b_save_file():
|
264 |
-
if g_load_format == "json":
|
265 |
-
b_save_json()
|
266 |
-
elif g_load_format == "list":
|
267 |
-
b_save_list()
|
268 |
-
|
269 |
-
|
270 |
-
def b_load_file():
|
271 |
-
if g_load_format == "json":
|
272 |
-
b_load_json()
|
273 |
-
elif g_load_format == "list":
|
274 |
-
b_load_list()
|
275 |
-
|
276 |
-
|
277 |
-
def set_global(load_json, load_list, json_key_text, json_key_path, batch):
|
278 |
-
global g_json_key_text, g_json_key_path, g_load_file, g_load_format, g_batch
|
279 |
-
|
280 |
-
g_batch = int(batch)
|
281 |
-
|
282 |
-
if (load_json != "None"):
|
283 |
-
g_load_format = "json"
|
284 |
-
g_load_file = load_json
|
285 |
-
elif (load_list != "None"):
|
286 |
-
g_load_format = "list"
|
287 |
-
g_load_file = load_list
|
288 |
-
else:
|
289 |
-
g_load_format = "list"
|
290 |
-
g_load_file = "demo.list"
|
291 |
-
|
292 |
-
g_json_key_text = json_key_text
|
293 |
-
g_json_key_path = json_key_path
|
294 |
-
|
295 |
-
b_load_file()
|
296 |
-
|
297 |
-
|
298 |
-
if __name__ == "__main__":
|
299 |
-
parser = argparse.ArgumentParser(description='Process some integers.')
|
300 |
-
parser.add_argument('--load_json', default="None", help='source file, like demo.json')
|
301 |
-
parser.add_argument('--is_share', default="False", help='whether webui is_share=True')
|
302 |
-
parser.add_argument('--load_list', default="None", help='source file, like demo.list')
|
303 |
-
parser.add_argument('--webui_port_subfix', default=9871, help='source file, like demo.list')
|
304 |
-
parser.add_argument('--json_key_text', default="text", help='the text key name in json, Default: text')
|
305 |
-
parser.add_argument('--json_key_path', default="wav_path", help='the path key name in json, Default: wav_path')
|
306 |
-
parser.add_argument('--g_batch', default=10, help='max number g_batch wav to display, Default: 10')
|
307 |
-
|
308 |
-
args = parser.parse_args()
|
309 |
-
|
310 |
-
set_global(args.load_json, args.load_list, args.json_key_text, args.json_key_path, args.g_batch)
|
311 |
-
|
312 |
-
with gr.Blocks() as demo:
|
313 |
-
|
314 |
-
with gr.Row():
|
315 |
-
btn_change_index = gr.Button("Change Index")
|
316 |
-
btn_submit_change = gr.Button("Submit Text")
|
317 |
-
btn_merge_audio = gr.Button("Merge Audio")
|
318 |
-
btn_delete_audio = gr.Button("Delete Audio")
|
319 |
-
btn_previous_index = gr.Button("Previous Index")
|
320 |
-
btn_next_index = gr.Button("Next Index")
|
321 |
-
|
322 |
-
with gr.Row():
|
323 |
-
index_slider = gr.Slider(
|
324 |
-
minimum=0, maximum=g_max_json_index, value=g_index, step=1, label="Index", scale=3
|
325 |
-
)
|
326 |
-
splitpoint_slider = gr.Slider(
|
327 |
-
minimum=0, maximum=120.0, value=0, step=0.1, label="Audio Split Point(s)", scale=3
|
328 |
-
)
|
329 |
-
btn_audio_split = gr.Button("Split Audio", scale=1)
|
330 |
-
btn_save_json = gr.Button("Save File", visible=True, scale=1)
|
331 |
-
btn_invert_selection = gr.Button("Invert Selection", scale=1)
|
332 |
-
|
333 |
-
with gr.Row():
|
334 |
-
with gr.Column():
|
335 |
-
for _ in range(0,g_batch):
|
336 |
-
with gr.Row():
|
337 |
-
text = gr.Textbox(
|
338 |
-
label = "Text",
|
339 |
-
visible = True,
|
340 |
-
scale=5
|
341 |
-
)
|
342 |
-
audio_output = gr.Audio(
|
343 |
-
label="Output Audio",
|
344 |
-
visible = True,
|
345 |
-
scale=5
|
346 |
-
)
|
347 |
-
audio_check = gr.Checkbox(
|
348 |
-
label="Yes",
|
349 |
-
show_label = True,
|
350 |
-
info = "Choose Audio",
|
351 |
-
scale=1
|
352 |
-
)
|
353 |
-
g_text_list.append(text)
|
354 |
-
g_audio_list.append(audio_output)
|
355 |
-
g_checkbox_list.append(audio_check)
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
with gr.Row():
|
360 |
-
batchsize_slider = gr.Slider(
|
361 |
-
minimum=1, maximum=g_batch, value=g_batch, step=1, label="Batch Size", scale=3, interactive=False
|
362 |
-
)
|
363 |
-
interval_slider = gr.Slider(
|
364 |
-
minimum=0, maximum=2, value=0, step=0.01, label="Interval", scale=3
|
365 |
-
)
|
366 |
-
btn_theme_dark = gr.Button("Light Theme", link="?__theme=light", scale=1)
|
367 |
-
btn_theme_light = gr.Button("Dark Theme", link="?__theme=dark", scale=1)
|
368 |
-
|
369 |
-
btn_change_index.click(
|
370 |
-
b_change_index,
|
371 |
-
inputs=[
|
372 |
-
index_slider,
|
373 |
-
batchsize_slider,
|
374 |
-
],
|
375 |
-
outputs=[
|
376 |
-
*g_text_list,
|
377 |
-
*g_audio_list,
|
378 |
-
*g_checkbox_list
|
379 |
-
],
|
380 |
-
)
|
381 |
-
|
382 |
-
|
383 |
-
btn_submit_change.click(
|
384 |
-
b_submit_change,
|
385 |
-
inputs=[
|
386 |
-
*g_text_list,
|
387 |
-
],
|
388 |
-
outputs=[
|
389 |
-
index_slider,
|
390 |
-
*g_text_list,
|
391 |
-
*g_audio_list,
|
392 |
-
*g_checkbox_list
|
393 |
-
],
|
394 |
-
)
|
395 |
-
|
396 |
-
btn_previous_index.click(
|
397 |
-
b_previous_index,
|
398 |
-
inputs=[
|
399 |
-
index_slider,
|
400 |
-
batchsize_slider,
|
401 |
-
],
|
402 |
-
outputs=[
|
403 |
-
index_slider,
|
404 |
-
*g_text_list,
|
405 |
-
*g_audio_list,
|
406 |
-
*g_checkbox_list
|
407 |
-
],
|
408 |
-
)
|
409 |
-
|
410 |
-
btn_next_index.click(
|
411 |
-
b_next_index,
|
412 |
-
inputs=[
|
413 |
-
index_slider,
|
414 |
-
batchsize_slider,
|
415 |
-
],
|
416 |
-
outputs=[
|
417 |
-
index_slider,
|
418 |
-
*g_text_list,
|
419 |
-
*g_audio_list,
|
420 |
-
*g_checkbox_list
|
421 |
-
],
|
422 |
-
)
|
423 |
-
|
424 |
-
btn_delete_audio.click(
|
425 |
-
b_delete_audio,
|
426 |
-
inputs=[
|
427 |
-
*g_checkbox_list
|
428 |
-
],
|
429 |
-
outputs=[
|
430 |
-
index_slider,
|
431 |
-
*g_text_list,
|
432 |
-
*g_audio_list,
|
433 |
-
*g_checkbox_list
|
434 |
-
]
|
435 |
-
)
|
436 |
-
|
437 |
-
btn_merge_audio.click(
|
438 |
-
b_merge_audio,
|
439 |
-
inputs=[
|
440 |
-
interval_slider,
|
441 |
-
*g_checkbox_list
|
442 |
-
],
|
443 |
-
outputs=[
|
444 |
-
index_slider,
|
445 |
-
*g_text_list,
|
446 |
-
*g_audio_list,
|
447 |
-
*g_checkbox_list
|
448 |
-
]
|
449 |
-
)
|
450 |
-
|
451 |
-
btn_audio_split.click(
|
452 |
-
b_audio_split,
|
453 |
-
inputs=[
|
454 |
-
splitpoint_slider,
|
455 |
-
*g_checkbox_list
|
456 |
-
],
|
457 |
-
outputs=[
|
458 |
-
index_slider,
|
459 |
-
*g_text_list,
|
460 |
-
*g_audio_list,
|
461 |
-
*g_checkbox_list
|
462 |
-
]
|
463 |
-
)
|
464 |
-
|
465 |
-
btn_invert_selection.click(
|
466 |
-
b_invert_selection,
|
467 |
-
inputs=[
|
468 |
-
*g_checkbox_list
|
469 |
-
],
|
470 |
-
outputs=[
|
471 |
-
*g_checkbox_list
|
472 |
-
]
|
473 |
-
)
|
474 |
-
|
475 |
-
btn_save_json.click(
|
476 |
-
b_save_file
|
477 |
-
)
|
478 |
-
|
479 |
-
demo.load(
|
480 |
-
b_change_index,
|
481 |
-
inputs=[
|
482 |
-
index_slider,
|
483 |
-
batchsize_slider,
|
484 |
-
],
|
485 |
-
outputs=[
|
486 |
-
*g_text_list,
|
487 |
-
*g_audio_list,
|
488 |
-
*g_checkbox_list
|
489 |
-
],
|
490 |
-
)
|
491 |
-
|
492 |
-
demo.launch(
|
493 |
-
server_name="0.0.0.0",
|
494 |
-
inbrowser=True,
|
495 |
-
quiet=True,
|
496 |
-
share=eval(args.is_share),
|
497 |
-
server_port=int(args.webui_port_subfix)
|
498 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/uvr5/bs_roformer/__init__.py
DELETED
File without changes
|
tools/uvr5/bs_roformer/attend.py
DELETED
@@ -1,120 +0,0 @@
|
|
1 |
-
from functools import wraps
|
2 |
-
from packaging import version
|
3 |
-
from collections import namedtuple
|
4 |
-
|
5 |
-
import torch
|
6 |
-
from torch import nn, einsum
|
7 |
-
import torch.nn.functional as F
|
8 |
-
|
9 |
-
from einops import rearrange, reduce
|
10 |
-
|
11 |
-
# constants
|
12 |
-
|
13 |
-
FlashAttentionConfig = namedtuple('FlashAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])
|
14 |
-
|
15 |
-
# helpers
|
16 |
-
|
17 |
-
def exists(val):
|
18 |
-
return val is not None
|
19 |
-
|
20 |
-
def default(v, d):
|
21 |
-
return v if exists(v) else d
|
22 |
-
|
23 |
-
def once(fn):
|
24 |
-
called = False
|
25 |
-
@wraps(fn)
|
26 |
-
def inner(x):
|
27 |
-
nonlocal called
|
28 |
-
if called:
|
29 |
-
return
|
30 |
-
called = True
|
31 |
-
return fn(x)
|
32 |
-
return inner
|
33 |
-
|
34 |
-
print_once = once(print)
|
35 |
-
|
36 |
-
# main class
|
37 |
-
|
38 |
-
class Attend(nn.Module):
|
39 |
-
def __init__(
|
40 |
-
self,
|
41 |
-
dropout = 0.,
|
42 |
-
flash = False,
|
43 |
-
scale = None
|
44 |
-
):
|
45 |
-
super().__init__()
|
46 |
-
self.scale = scale
|
47 |
-
self.dropout = dropout
|
48 |
-
self.attn_dropout = nn.Dropout(dropout)
|
49 |
-
|
50 |
-
self.flash = flash
|
51 |
-
assert not (flash and version.parse(torch.__version__) < version.parse('2.0.0')), 'in order to use flash attention, you must be using pytorch 2.0 or above'
|
52 |
-
|
53 |
-
# determine efficient attention configs for cuda and cpu
|
54 |
-
|
55 |
-
self.cpu_config = FlashAttentionConfig(True, True, True)
|
56 |
-
self.cuda_config = None
|
57 |
-
|
58 |
-
if not torch.cuda.is_available() or not flash:
|
59 |
-
return
|
60 |
-
|
61 |
-
device_properties = torch.cuda.get_device_properties(torch.device('cuda'))
|
62 |
-
|
63 |
-
if device_properties.major == 8 and device_properties.minor == 0:
|
64 |
-
print_once('A100 GPU detected, using flash attention if input tensor is on cuda')
|
65 |
-
self.cuda_config = FlashAttentionConfig(True, False, False)
|
66 |
-
else:
|
67 |
-
print_once('Non-A100 GPU detected, using math or mem efficient attention if input tensor is on cuda')
|
68 |
-
self.cuda_config = FlashAttentionConfig(False, True, True)
|
69 |
-
|
70 |
-
def flash_attn(self, q, k, v):
|
71 |
-
_, heads, q_len, _, k_len, is_cuda, device = *q.shape, k.shape[-2], q.is_cuda, q.device
|
72 |
-
|
73 |
-
if exists(self.scale):
|
74 |
-
default_scale = q.shape[-1] ** -0.5
|
75 |
-
q = q * (self.scale / default_scale)
|
76 |
-
|
77 |
-
# Check if there is a compatible device for flash attention
|
78 |
-
|
79 |
-
config = self.cuda_config if is_cuda else self.cpu_config
|
80 |
-
|
81 |
-
# pytorch 2.0 flash attn: q, k, v, mask, dropout, softmax_scale
|
82 |
-
|
83 |
-
with torch.backends.cuda.sdp_kernel(**config._asdict()):
|
84 |
-
out = F.scaled_dot_product_attention(
|
85 |
-
q, k, v,
|
86 |
-
dropout_p = self.dropout if self.training else 0.
|
87 |
-
)
|
88 |
-
|
89 |
-
return out
|
90 |
-
|
91 |
-
def forward(self, q, k, v):
|
92 |
-
"""
|
93 |
-
einstein notation
|
94 |
-
b - batch
|
95 |
-
h - heads
|
96 |
-
n, i, j - sequence length (base sequence length, source, target)
|
97 |
-
d - feature dimension
|
98 |
-
"""
|
99 |
-
|
100 |
-
q_len, k_len, device = q.shape[-2], k.shape[-2], q.device
|
101 |
-
|
102 |
-
scale = default(self.scale, q.shape[-1] ** -0.5)
|
103 |
-
|
104 |
-
if self.flash:
|
105 |
-
return self.flash_attn(q, k, v)
|
106 |
-
|
107 |
-
# similarity
|
108 |
-
|
109 |
-
sim = einsum(f"b h i d, b h j d -> b h i j", q, k) * scale
|
110 |
-
|
111 |
-
# attention
|
112 |
-
|
113 |
-
attn = sim.softmax(dim=-1)
|
114 |
-
attn = self.attn_dropout(attn)
|
115 |
-
|
116 |
-
# aggregate values
|
117 |
-
|
118 |
-
out = einsum(f"b h i j, b h j d -> b h i d", attn, v)
|
119 |
-
|
120 |
-
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|