This repository was archived by the owner on Oct 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 942
Expand file tree
/
Copy pathconfig.py
More file actions
330 lines (271 loc) · 10.5 KB
/
config.py
File metadata and controls
330 lines (271 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""Configuration classes"""
from dataclasses import dataclass, field
from typing import Optional, Tuple
@dataclass
class MelAudioConfig:
filter_length: int = 1024
hop_length: int = 256
win_length: int = 1024
mel_channels: int = 80
sample_rate: int = 22050
sample_bytes: int = 2
channels: int = 1
mel_fmin: float = 0.0
mel_fmax: Optional[float] = None
@dataclass
class ModelAudioConfig:
resblock: str
resblock_kernel_sizes: Tuple[int, ...]
resblock_dilation_sizes: Tuple[Tuple[int, ...], ...]
upsample_rates: Tuple[int, ...]
upsample_initial_channel: int
upsample_kernel_sizes: Tuple[int, ...]
@staticmethod
def low_quality() -> "ModelAudioConfig":
return ModelAudioConfig(
resblock="2",
resblock_kernel_sizes=(3, 5, 7),
resblock_dilation_sizes=(
(1, 2),
(2, 6),
(3, 12),
),
upsample_rates=(8, 8, 4),
upsample_initial_channel=256,
upsample_kernel_sizes=(16, 16, 8),
)
@staticmethod
def high_quality() -> "ModelAudioConfig":
return ModelAudioConfig(
resblock="1",
resblock_kernel_sizes=(3, 7, 11),
resblock_dilation_sizes=(
(1, 3, 5),
(1, 3, 5),
(1, 3, 5),
),
upsample_rates=(8, 8, 2, 2),
upsample_initial_channel=512,
upsample_kernel_sizes=(16, 16, 4, 4),
)
@dataclass
class ModelConfig:
num_symbols: int
n_speakers: int
audio: ModelAudioConfig
mel: MelAudioConfig = field(default_factory=MelAudioConfig)
inter_channels: int = 192
hidden_channels: int = 192
filter_channels: int = 768
n_heads: int = 2
n_layers: int = 6
kernel_size: int = 3
p_dropout: float = 0.1
n_layers_q: int = 3
use_spectral_norm: bool = False
gin_channels: int = 0 # single speaker
use_sdp: bool = True # StochasticDurationPredictor
segment_size: int = 8192
@property
def is_multispeaker(self) -> bool:
return self.n_speakers > 1
@property
def resblock(self) -> str:
return self.audio.resblock
@property
def resblock_kernel_sizes(self) -> Tuple[int, ...]:
return self.audio.resblock_kernel_sizes
@property
def resblock_dilation_sizes(self) -> Tuple[Tuple[int, ...], ...]:
return self.audio.resblock_dilation_sizes
@property
def upsample_rates(self) -> Tuple[int, ...]:
return self.audio.upsample_rates
@property
def upsample_initial_channel(self) -> int:
return self.audio.upsample_initial_channel
@property
def upsample_kernel_sizes(self) -> Tuple[int, ...]:
return self.audio.upsample_kernel_sizes
def __post_init__(self):
if self.is_multispeaker and (self.gin_channels == 0):
self.gin_channels = 512
@dataclass
class TrainingConfig:
learning_rate: float = 2e-4
betas: Tuple[float, float] = field(default=(0.8, 0.99))
eps: float = 1e-9
# batch_size: int = 32
fp16_run: bool = False
lr_decay: float = 0.999875
init_lr_ratio: float = 1.0
warmup_epochs: int = 0
c_mel: int = 45
c_kl: float = 1.0
grad_clip: Optional[float] = None
# @dataclass
# class PhonemesConfig(DataClassJsonMixin):
# phoneme_separator: str = " "
# """Separator between individual phonemes in CSV input"""
# word_separator: str = "#"
# """Separator between word phonemes in CSV input (must not match phoneme_separator)"""
# phoneme_to_id: typing.Optional[typing.Dict[str, int]] = None
# pad: typing.Optional[str] = "_"
# bos: typing.Optional[str] = None
# eos: typing.Optional[str] = None
# blank: typing.Optional[str] = "#"
# blank_word: typing.Optional[str] = None
# blank_between: typing.Union[str, BlankBetween] = BlankBetween.WORDS
# blank_at_start: bool = True
# blank_at_end: bool = True
# simple_punctuation: bool = True
# punctuation_map: typing.Optional[typing.Dict[str, str]] = None
# separate: typing.Optional[typing.List[str]] = None
# separate_graphemes: bool = False
# separate_tones: bool = False
# tone_before: bool = False
# phoneme_map: typing.Optional[typing.Dict[str, typing.List[str]]] = None
# auto_bos_eos: bool = False
# minor_break: typing.Optional[str] = IPA.BREAK_MINOR.value
# major_break: typing.Optional[str] = IPA.BREAK_MAJOR.value
# break_phonemes_into_graphemes: bool = False
# break_phonemes_into_codepoints: bool = False
# drop_stress: bool = False
# symbols: typing.Optional[typing.List[str]] = None
# def split_word_phonemes(self, phonemes_str: str) -> typing.List[typing.List[str]]:
# """Split phonemes string into a list of lists (outer is words, inner is individual phonemes in each word)"""
# return [
# word_phonemes_str.split(self.phoneme_separator)
# if self.phoneme_separator
# else list(word_phonemes_str)
# for word_phonemes_str in phonemes_str.split(self.word_separator)
# ]
# def join_word_phonemes(self, word_phonemes: typing.List[typing.List[str]]) -> str:
# """Split phonemes string into a list of lists (outer is words, inner is individual phonemes in each word)"""
# return self.word_separator.join(
# self.phoneme_separator.join(wp) for wp in word_phonemes
# )
# class Phonemizer(str, Enum):
# SYMBOLS = "symbols"
# GRUUT = "gruut"
# ESPEAK = "espeak"
# EPITRAN = "epitran"
# class Aligner(str, Enum):
# KALDI_ALIGN = "kaldi_align"
# class TextCasing(str, Enum):
# LOWER = "lower"
# UPPER = "upper"
# class MetadataFormat(str, Enum):
# TEXT = "text"
# PHONEMES = "phonemes"
# PHONEME_IDS = "ids"
# @dataclass
# class DatasetConfig:
# name: str
# metadata_format: MetadataFormat = MetadataFormat.TEXT
# multispeaker: bool = False
# text_language: typing.Optional[str] = None
# audio_dir: typing.Optional[typing.Union[str, Path]] = None
# cache_dir: typing.Optional[typing.Union[str, Path]] = None
# def get_cache_dir(self, output_dir: typing.Union[str, Path]) -> Path:
# if self.cache_dir is not None:
# cache_dir = Path(self.cache_dir)
# else:
# cache_dir = Path("cache") / self.name
# if not cache_dir.is_absolute():
# cache_dir = Path(output_dir) / str(cache_dir)
# return cache_dir
# @dataclass
# class AlignerConfig:
# aligner: typing.Optional[Aligner] = None
# casing: typing.Optional[TextCasing] = None
# @dataclass
# class InferenceConfig:
# length_scale: float = 1.0
# noise_scale: float = 0.667
# noise_w: float = 0.8
# @dataclass
# class TrainingConfig(DataClassJsonMixin):
# seed: int = 1234
# epochs: int = 10000
# learning_rate: float = 2e-4
# betas: typing.Tuple[float, float] = field(default=(0.8, 0.99))
# eps: float = 1e-9
# batch_size: int = 32
# fp16_run: bool = False
# lr_decay: float = 0.999875
# segment_size: int = 8192
# init_lr_ratio: float = 1.0
# warmup_epochs: int = 0
# c_mel: int = 45
# c_kl: float = 1.0
# grad_clip: typing.Optional[float] = None
# min_seq_length: typing.Optional[int] = None
# max_seq_length: typing.Optional[int] = None
# min_spec_length: typing.Optional[int] = None
# max_spec_length: typing.Optional[int] = None
# min_speaker_utterances: typing.Optional[int] = None
# last_epoch: int = 1
# global_step: int = 1
# best_loss: typing.Optional[float] = None
# audio: AudioConfig = field(default_factory=AudioConfig)
# model: ModelConfig = field(default_factory=ModelConfig)
# phonemes: PhonemesConfig = field(default_factory=PhonemesConfig)
# text_aligner: AlignerConfig = field(default_factory=AlignerConfig)
# text_language: typing.Optional[str] = None
# phonemizer: typing.Optional[Phonemizer] = None
# datasets: typing.List[DatasetConfig] = field(default_factory=list)
# inference: InferenceConfig = field(default_factory=InferenceConfig)
# version: int = 1
# git_commit: str = ""
# @property
# def is_multispeaker(self):
# return self.model.is_multispeaker or any(d.multispeaker for d in self.datasets)
# def save(self, config_file: typing.TextIO):
# """Save config as JSON to a file"""
# json.dump(self.to_dict(), config_file, indent=4)
# def get_speaker_id(self, dataset_name: str, speaker_name: str) -> int:
# if self.speaker_id_map is None:
# self.speaker_id_map = {}
# full_speaker_name = f"{dataset_name}_{speaker_name}"
# speaker_id = self.speaker_id_map.get(full_speaker_name)
# if speaker_id is None:
# speaker_id = len(self.speaker_id_map)
# self.speaker_id_map[full_speaker_name] = speaker_id
# return speaker_id
# @staticmethod
# def load(config_file: typing.TextIO) -> "TrainingConfig":
# """Load config from a JSON file"""
# return TrainingConfig.from_json(config_file.read())
# @staticmethod
# def load_and_merge(
# config: "TrainingConfig",
# config_files: typing.Iterable[typing.Union[str, Path, typing.TextIO]],
# ) -> "TrainingConfig":
# """Loads one or more JSON configuration files and overlays them on top of an existing config"""
# base_dict = config.to_dict()
# for maybe_config_file in config_files:
# if isinstance(maybe_config_file, (str, Path)):
# # File path
# config_file = open(maybe_config_file, "r", encoding="utf-8")
# else:
# # File object
# config_file = maybe_config_file
# with config_file:
# # Load new config and overlay on existing config
# new_dict = json.load(config_file)
# TrainingConfig.recursive_update(base_dict, new_dict)
# return TrainingConfig.from_dict(base_dict)
# @staticmethod
# def recursive_update(
# base_dict: typing.Dict[typing.Any, typing.Any],
# new_dict: typing.Mapping[typing.Any, typing.Any],
# ) -> None:
# """Recursively overwrites values in base dictionary with values from new dictionary"""
# for key, value in new_dict.items():
# if isinstance(value, collections.Mapping) and (
# base_dict.get(key) is not None
# ):
# TrainingConfig.recursive_update(base_dict[key], value)
# else:
# base_dict[key] = value