-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
1962 lines (1780 loc) · 63 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from src.logger import progress_bar, Question
import logging
from collections import OrderedDict
from dataclasses import dataclass, asdict
import functools
from typing import (
Any,
Callable,
Dict,
Protocol,
Type,
Tuple,
Literal,
List,
Optional,
TYPE_CHECKING,
Union,
)
import math
from pathlib import Path
from random import shuffle, randint
import os
from warnings import simplefilter
import cpuinfo
from dataclasses_json import dataclass_json, Undefined
from rich.progress import Progress
import rich.prompt as rp
import torch
from torch.amp import GradScaler
from torch.utils.data import DataLoader
import torch.distributed as dist
import torch.nn.functional as F
import torch.optim.swa_utils as S
from torch.nn.parallel import DistributedDataParallel as DDP
from torchaudio import functional as Fa
import numpy as np
from scipy import signal
from scipy.io import wavfile
from sklearn.cluster import MiniBatchKMeans
import faiss
from src.models.rvc import (
SynthesizerTrnMs256NSFsid,
SynthesizerTrnMs768NSFsid,
MultiPeriodDiscriminator,
MultiPeriodDiscriminatorV2,
RVCConfig,
)
from src.models.hubert import load_hubert
from src.models.pitch import compute_pitch_from_audio
from src.utils import (
load_checkpoint,
save_checkpoint,
latest_checkpoint_path,
feature_loss,
discriminator_loss,
generator_loss,
kl_loss,
TextAudioLoaderMultiNSFsid,
TextAudioCollateMultiNSFsid,
DistributedBucketSampler,
torch_spec_to_mel,
torch_mel_spectrogram,
load_audio,
get_rms,
)
if TYPE_CHECKING:
from lomo_optim import AdaLomo, Lomo
from came_pytorch import CAME
from adan import Adan
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = str(randint(20000, 55555))
USE_WANDB = True
gt = "gtwaves/"
sixteenk = "16kwaves/"
features = "features/"
f0 = "f0/"
f0coarse = "f0nsf/"
hubert = "hubert_base.pt"
hubert_batch = 4
assert Path(
hubert
).exists(), "Please download the pretrained Hubert model from Hugging Face"
hubert, saved_cfg, task = load_hubert(hubert, None, return_cfg=True)
simplefilter("ignore")
global_step = 0
optimal_cores: int = math.ceil(os.cpu_count() / 3)
noise_batch = 8 # batch size for pitch extraction
if USE_WANDB:
import wandb
USE_WANDB = wandb.login()
OptimizerList = Literal[
"adam",
"adamw",
"adamw_8bit",
"adan",
"lomo",
"adalomo",
"came",
]
OptimizerType = Union[
torch.optim.Optimizer,
"AdaLomo",
"Lomo",
"CAME",
"Adan",
]
@dataclass_json(undefined=Undefined.EXCLUDE)
@dataclass
class TrainParameters:
betas: List[float]
eps: float
lr_decay: float
segment_size: int
init_lr_ratio: float
warmup_epochs: int
c_mel: int
c_kl: float
@dataclass_json
@dataclass
class DataParameters:
max_wav_value: float
sampling_rate: int
filter_length: int
hop_length: int
win_length: int
n_mel_channels: int
mel_fmin: float
mel_fmax: Optional[float]
@dataclass_json
@dataclass
class ModelParameters:
inter_channels: int
hidden_channels: int
filter_channels: int
n_heads: int
n_layers: int
kernel_size: int
p_dropout: int
resblock: str
resblock_kernel_sizes: List[int]
resblock_dilation_sizes: List[List[int]]
upsample_rates: List[int]
upsample_initial_channel: int
upsample_kernel_sizes: List[int]
use_spectral_norm: bool
gin_channels: int
spk_embed_dim: int
@dataclass_json
@dataclass
class TrainingParameters:
train: TrainParameters
data: DataParameters
model: ModelParameters
version: str = "v2"
@dataclass
class InputParameters:
training_files: Path
model_files: Path
used_device: torch.device
dtype: torch.dtype
cache_data: bool = True
save_every: int = 200
latest_only: bool = False
pitch_extractor: str = "rmvpe"
pretrain_g: str = ""
pretrain_d: str = ""
version: str = "v2"
batch_size: int = 36
gradient_accumulation_steps: int = 1
secondary_model: Literal["none", "swa", "ema"] = "none"
secondary_start: int = -1 # -1 to disable
swa_lr: float = 5e-4
ema_delta: float = 0.995 # default: 0.995
log_interval: int = 5
seed: int = 1337
epochs: int = 1000
learning_rate: float = 2e-4
clip_grad: float = 0
optimizer: OptimizerList = "adamw"
compile_optimizer: bool = False # should net a decent speedup
scheduler: Literal["exponential", "constant", "cosine"] = "constant"
def get_rvc_config(self) -> RVCConfig:
return RVCConfig(
device=self.used_device,
dtype=self.dtype,
)
class TrainingLogger(Protocol):
def log(self, log: Dict[str, Any]) -> None: ...
def finish(self) -> None: ...
class CLITrainingLogger:
last_params = {}
def log(self, log: Dict[str, Any]) -> None:
out = ""
color_params = {}
for k, v in log.items():
if k in self.last_params:
if self.last_params[k] == v:
color_params[k] = "yellow"
elif self.last_params[k] < v:
color_params[k] = "green"
else:
color_params[k] = "red"
continue
if isinstance(v, (int, float)):
self.last_params[k] = v
color_params[k] = "green"
log_len = len(log)
for i, (k, v) in enumerate(log.items()):
out += f"[bold]{k}[/]: [{color_params[k]}]{str(v)}[/]"
if i < log_len - 1:
out += " | "
logger.info(out, extra={"markup": True})
def finish(self) -> None:
return
class Slicer:
def __init__(
self,
sr: int,
silence_threshold: float = -40,
min_length: int = 5000,
min_interval: int = 300,
hop_length: int = 20,
max_sil_kept: int = 5000,
):
min_interval = sr * min_interval / 1000
self.threshold = 10 ** (silence_threshold / 20.0)
self.hop_length = round(sr * hop_length / 1000)
self.win_size = min(round(min_interval), 4 * self.hop_length)
self.min_length = round(sr * min_length / 1000 / self.hop_length)
self.min_interval = round(min_interval / self.hop_length)
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_length)
def _apply_slice(self, waveform, begin, end):
if len(waveform.shape) > 1:
return waveform[
:,
begin * self.hop_length : min(waveform.shape[1], end * self.hop_length),
]
else:
return waveform[
begin * self.hop_length : min(waveform.shape[0], end * self.hop_length)
]
def __call__(self, waveform):
if len(waveform.shape) > 1:
samples = waveform.mean(axis=0)
else:
samples = waveform
if samples.shape[0] <= self.min_length:
return [waveform]
rms_list = get_rms(
y=samples, frame_length=self.win_size, hop_length=self.hop_length
).squeeze(0)
sil_tags = []
silence_start = None
clip_start = 0
for i, rms in enumerate(rms_list):
if rms < self.threshold:
if silence_start is None:
silence_start = i
continue
if silence_start is None:
continue
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
need_slice_middle = (
i - silence_start >= self.min_interval
and i - clip_start >= self.min_length
)
if not is_leading_silence and not need_slice_middle:
silence_start = None
continue
if i - silence_start <= self.max_sil_kept:
pos = torch.argmin(rms_list[silence_start : i + 1]) + silence_start
if silence_start == 0:
sil_tags.append((0, pos))
else:
sil_tags.append((pos, pos))
clip_start = pos
elif i - silence_start <= self.max_sil_kept * 2:
pos = (
torch.argmin(
rms_list[
i
- self.max_sil_kept : silence_start
+ self.max_sil_kept
+ 1
]
)
+ i
- self.max_sil_kept
)
pos_l = (
torch.argmin(
rms_list[silence_start : silence_start + self.max_sil_kept + 1]
)
+ silence_start
)
pos_r = (
torch.argmin(rms_list[i - self.max_sil_kept : i + 1])
+ i
- self.max_sil_kept
)
if silence_start == 0:
sil_tags.append((0, pos_r))
clip_start = pos_r
else:
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
clip_start = max(pos_r, pos)
else:
pos_l = (
torch.argmin(
rms_list[silence_start : silence_start + self.max_sil_kept + 1]
)
+ silence_start
)
pos_r = (
torch.argmin(rms_list[i - self.max_sil_kept : i + 1])
+ i
- self.max_sil_kept
)
if silence_start == 0:
sil_tags.append((0, pos_r))
else:
sil_tags.append((pos_l, pos_r))
clip_start = pos_r
silence_start = None
total_frames = rms_list.shape[0]
if (
silence_start is not None
and total_frames - silence_start >= self.min_interval
):
silence_end = min(total_frames, silence_start + self.max_sil_kept)
pos = (
torch.argmin(rms_list[silence_start : silence_end + 1]) + silence_start
)
sil_tags.append((pos, total_frames))
if len(sil_tags) == 0:
return [waveform]
else:
chunks = []
if sil_tags[0][0] > 0:
chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
for i in range(len(sil_tags) - 1):
chunks.append(
self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0])
)
if sil_tags[-1][1] < total_frames:
chunks.append(
self._apply_slice(waveform, sil_tags[-1][1], total_frames)
)
return chunks
def train_index(output_dir: Path, input_parameters: InputParameters):
out = input_parameters.model_files / "checkpoint.index"
feature_dir = output_dir / features
listdir_res = list(os.listdir(feature_dir))
npys = []
for name in sorted(listdir_res):
phone = np.load((feature_dir / name).as_posix())
npys.append(phone)
big_npy = np.concatenate(npys, 0)
big_npy_idx = np.arange(big_npy.shape[0])
np.random.shuffle(big_npy_idx)
big_npy = big_npy[big_npy_idx]
if big_npy.shape[0] > 2e5:
big_npy = (
MiniBatchKMeans(
n_clusters=10000,
verbose=True,
batch_size=256 * optimal_cores,
compute_labels=False,
init="random",
)
.fit(big_npy)
.cluster_centers_
)
np.save((output_dir / "total_fea.npy").as_posix(), big_npy)
n_ivf = min(int(16 * np.sqrt(big_npy.shape[0])), big_npy.shape[0] // 39)
index = faiss.index_factory(
256 if input_parameters.version == "v1" else 768, f"IVF{n_ivf},Flat"
)
index_ivf = faiss.extract_index_ivf(index)
index_ivf.nprobe = 1
index.train(big_npy)
faiss.write_index(
index,
(
output_dir / f"trained_IVF{n_ivf}_Flat_nprobe_{index_ivf.nprobe}.index"
).as_posix(),
)
batch_size_add = 8192
for i in range(0, big_npy.shape[0], batch_size_add):
index.add(big_npy[i : i + batch_size_add])
faiss.write_index(
index,
out.as_posix(),
)
def preprocess(
input_dir: Path, output_dir: Path, progress: Progress, sr: int = 40000
) -> Path:
assert input_dir.exists(), f"{input_dir} does not exist"
output_dir.mkdir(exist_ok=True)
slicer = Slicer(
sr,
silence_threshold=-42,
min_length=1500,
min_interval=400,
hop_length=15,
max_sil_kept=500,
)
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=sr)
per = 3.0
overlap = 0.3
tail = per + overlap
max = 0.9
alpha = 0.75
gt_wavs = output_dir / gt
wavs16k = output_dir / sixteenk
gt_wavs.mkdir(exist_ok=True)
wavs16k.mkdir(exist_ok=True)
def norm_write(tmp_audio: torch.Tensor, idx0, idx1):
tmp_max = torch.abs(tmp_audio).max()
if tmp_max > 2.5:
logger.debug(f"{idx0}-{idx1} is filtered")
return
tmp_audio = (tmp_audio / tmp_max * (max * alpha)) + (1 - alpha) * tmp_audio
# the line below WILL/SHOULD stay here, since I've spent ~3h looking why half the audio was cut off
# tmp_audio = ((tmp_audio / tmp_max * (max * alpha)) + (1 - alpha)) * tmp_audio
wavfile.write(gt_wavs / f"{idx0}-{idx1}.wav", sr, tmp_audio.float().numpy())
tmp_audio = Fa.resample(tmp_audio, sr, 16000)
wavfile.write(wavs16k / f"{idx0}-{idx1}.wav", 16000, tmp_audio.float().numpy())
for idx0, f in enumerate(os.listdir(input_dir)):
input = input_dir / f
try:
audio, _ = load_audio(input, sr)
audio = signal.lfilter(bh, ah, audio)
audio = torch.from_numpy(audio.astype(np.float32))
idx1 = 0
slices = slicer(audio)
for audio in progress.track(
slices, total=len(slices), description="Splitting files..."
):
i = 0
while True:
start = int(sr * (per - overlap) * i)
i += 1
if len(audio[start:]) > tail * sr:
tmp_audio = audio[start : start + int(per * sr)]
norm_write(tmp_audio, idx0, idx1)
idx1 += 1
else:
tmp_audio = audio[start:]
idx1 += 1
break
norm_write(tmp_audio, idx0, idx1)
except Exception as e:
logger.error(f"Failed to process {input.name}:", e)
return output_dir
def extract_features(
output_dir: Path,
input_parameters: InputParameters,
progress: Progress,
) -> Path:
gt_wavs = output_dir / gt
features_dir = output_dir / features
features_dir.mkdir(exist_ok=True)
dtype = input_parameters.dtype
hubert.to(input_parameters.used_device, dtype)
hubert.eval()
files = os.listdir(gt_wavs)
files = list(map(lambda x: gt_wavs / x, files))
for f in progress.track(
files, total=len(files), description="Extracting features..."
):
out_file = features_dir / (f.stem + ".npy")
feats = read_wave(f, normalize=saved_cfg.task.normalize)
padding_mask = torch.BoolTensor(feats.shape).fill_(False)
inputs = {
"source": feats.to(input_parameters.used_device, dtype),
"padding_mask": padding_mask.to(input_parameters.used_device),
"output_layer": 9 if input_parameters.version == "v1" else 12,
}
with torch.no_grad():
logits = hubert.extract_features(**inputs)
feats = (
hubert.final_proj(logits[0])
if input_parameters.version == "v1"
else logits[0]
)
feats = feats.squeeze(0).float().cpu().numpy()
if np.isnan(feats).sum() == 0:
np.save(out_file, feats, allow_pickle=False)
else:
logger.warn(f"NaNs found in {f.name}, skipping")
return features_dir
def extract_f0(
output_dir: Path,
input_parameters: InputParameters,
progress: Progress,
) -> Path:
f0_dir = output_dir / f0
f0_coarse_dir = output_dir / f0coarse
f0_dir.mkdir(exist_ok=True)
f0_coarse_dir.mkdir(exist_ok=True)
files = os.listdir(output_dir / sixteenk)
files = filter(lambda x: "spec" not in x, files)
files = list(map(lambda x: output_dir / sixteenk / x, files))
total = len(files)
rvc_config = input_parameters.get_rvc_config()
for file in progress.track(files, total=total, description="Extracting F0..."):
wav, _ = load_audio(file, 16000)
(f0_coarse, f0_), wav = compute_pitch_from_audio(
wav,
rvc_config=rvc_config,
extractors=input_parameters.pitch_extractor,
skip_preprocess=True,
)
f0_.squeeze_()
f0_coarse.squeeze_()
np.save(
f0_coarse_dir / f"{file.stem}.npy",
f0_coarse.cpu().int().numpy(),
allow_pickle=False,
)
np.save(
f0_dir / f"{file.stem}.npy", f0_.cpu().float().numpy(), allow_pickle=False
)
def write_filelist(output_dir: Path, input_parameters: InputParameters) -> None:
gt_wavs = output_dir / gt
opt = []
for file in os.listdir(gt_wavs):
file = gt_wavs / file
gt_wav = file.as_posix()
feature = (output_dir / features / f"{file.stem}.npy").as_posix()
f0_ = (output_dir / f0 / f"{file.stem}.npy").as_posix()
f0_coarse = (output_dir / f0coarse / f"{file.stem}.npy").as_posix()
spkid = "0"
opt.append(f"{gt_wav}|{feature}|{f0_coarse}|{f0_}|{spkid}")
opt.append(
"train_logs/mute/gtwaves/mute40k.wav|train_logs/mute/features/mute.npy|train_logs/mute/f0nsf/mute.wav.npy|train_logs/mute/f0/mute.wav.npy|0"
)
with open(input_parameters.model_files / "filelist.txt", "w+") as f:
f.write("\n".join(opt))
def read_wave(wav_path: Path, normalize: bool = False) -> torch.Tensor:
wav, sr = load_audio(wav_path.as_posix(), 16000)
assert sr == 16000, "no idea how this could happen, but best to check just in case"
feats = torch.from_numpy(wav).float()
if feats.dim() == 2:
feats = feats.mean(-1)
assert feats.dim() == 1, feats.dim()
if normalize:
with torch.no_grad():
feats = F.layer_norm(feats, feats.shape)
feats = feats.view(1, -1)
return feats
def setup_logging(
input_parameters: InputParameters, training_parameters: TrainingParameters
) -> TrainingLogger:
if not USE_WANDB:
return CLITrainingLogger()
x = wandb.init(
name=input_parameters.model_files.name,
project="rvc",
config={**asdict(training_parameters.train), **asdict(input_parameters)},
)
return x
def choose_models(
version: str, hyperparameters: TrainingParameters
) -> Tuple[Type, Type]:
"""return: [G, D]"""
if version.lower() == "v2":
G, D = SynthesizerTrnMs768NSFsid, MultiPeriodDiscriminatorV2
else:
G, D = SynthesizerTrnMs256NSFsid, MultiPeriodDiscriminator
def g():
return G(
hyperparameters.data.filter_length // 2 + 1,
hyperparameters.train.segment_size // hyperparameters.data.hop_length,
sr=hyperparameters.data.sampling_rate,
**asdict(hyperparameters.model),
)
def d():
return D(hyperparameters.model.use_spectral_norm)
return g, d
def choose_optimizer(
optimizer: OptimizerList,
model: torch.nn.Module,
lr: float,
betas: List[float],
eps: float,
weight_decay: float = 1e-2, # default adamw value
) -> Tuple[OptimizerType, bool]:
"""return: (optimizer, can_compile)"""
if optimizer == "adamw":
return (
torch.optim.AdamW(
model.parameters(),
lr=lr,
betas=betas,
eps=eps,
foreach=True,
fused=False, # fused doesn't seem to work?
amsgrad=True, # try to use amsgrad to stabilize training??
weight_decay=weight_decay,
),
True,
)
elif optimizer == "adamw_8bit":
from bitsandbytes.optim import AdamW8bit
return (
AdamW8bit(
model.parameters(),
lr=lr,
betas=betas,
eps=eps,
amsgrad=True,
optim_bits=16, # base on fp16
percentile_clipping=99,
weight_decay=weight_decay,
),
True,
)
elif optimizer == "adam":
return (
torch.optim.Adam(
model.parameters(),
lr=lr,
betas=betas,
eps=eps,
amsgrad=True,
weight_decay=weight_decay,
foreach=True,
fused=False,
),
True,
)
elif optimizer == "adalomo":
from lomo_optim import AdaLomo
return (
AdaLomo(
model,
lr=lr,
eps=(eps, 0.001),
clip_grad_norm=1.0,
weight_decay=weight_decay,
clip_threshold=0.99,
),
False,
)
elif optimizer == "lomo":
from lomo_optim import Lomo
return (
Lomo(
model,
lr=lr,
clip_grad_norm=1.0,
weight_decay=weight_decay,
clip_threshold=0.99,
),
False,
)
elif optimizer == "came":
from came_pytorch import CAME
return (
CAME(
model.parameters(),
lr=lr,
betas=[
0.9,
]
+ betas,
weight_decay=weight_decay,
clip_threshold=0.99,
),
False,
)
elif optimizer == "adan":
from adan import Adan
return (
Adan(
model.parameters(),
betas=[
0.9,
]
+ betas,
lr=lr,
eps=eps,
fused=True,
no_prox=True, # reproduce adamw behaviour
),
False,
)
def choose_scheduler(
sched: Literal[
"exponential",
"constant",
"cosine",
"cosine_annealing_with_warm_restarts",
"swa",
],
optimizer: torch.optim.Optimizer,
gamma: float,
last_epoch: int,
max_epochs: int,
):
if sched == "exponential":
return torch.optim.lr_scheduler.ExponentialLR(
optimizer=optimizer, gamma=gamma, last_epoch=last_epoch
)
elif sched == "constant":
return torch.optim.lr_scheduler.ConstantLR(
optimizer=optimizer, last_epoch=last_epoch
)
elif sched == "cosine":
return torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer=optimizer, T_max=max_epochs, eta_min=1e-10, last_epoch=last_epoch
)
elif sched == "cosine_annealing_with_warm_restarts":
return torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(
optimizer=optimizer,
T_0=max_epochs // 20,
T_mult=2,
eta_min=1e-10,
last_epoch=last_epoch,
)
elif sched == "swa":
return S.SWALR(optimizer=optimizer, swa_lr=gamma)
return None
def slice_segments(
x: torch.Tensor, ids_str: str, segment_size: int = 4
) -> torch.Tensor:
ret = torch.zeros_like(x[:, :, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, :, idx_str:idx_end]
return ret
def save_small_model(
ckpt: torch.nn.Module,
name: str,
epoch: int,
hps: TrainingParameters,
input_parameters: InputParameters,
):
opt = OrderedDict()
opt["weight"] = {}
dtype = input_parameters.dtype
for key in ckpt.keys():
if "enc_q" in key:
continue
opt["weight"][key] = ckpt[key].to(dtype=dtype)
opt["config"] = [
hps.data.filter_length // 2 + 1,
32,
hps.model.inter_channels,
hps.model.hidden_channels,
hps.model.filter_channels,
hps.model.n_heads,
hps.model.n_layers,
hps.model.kernel_size,
hps.model.p_dropout,
hps.model.resblock,
hps.model.resblock_kernel_sizes,
hps.model.resblock_dilation_sizes,
hps.model.upsample_rates,
hps.model.upsample_initial_channel,
hps.model.upsample_kernel_sizes,
hps.model.spk_embed_dim,
hps.model.gin_channels,
hps.data.sampling_rate,
]
opt["info"] = f"{epoch}epoch"
opt["sr"] = hps.data.sampling_rate
opt["f0"] = 1
opt["version"] = input_parameters.version
(Path("models/") / name).mkdir(exist_ok=True, parents=True)
torch.save(opt, f"models/{name}/checkpoint.pth")
return "Success."
def run(
rank: int, n_gpus: int, input: InputParameters, hyperparameters: TrainingParameters
):
global global_step
if n_gpus > 1:
raise ValueError("Only single-gpu training is supported for now")
dist.init_process_group(
backend="gloo", init_method="env://", world_size=n_gpus, rank=rank
)
# set seed
torch.manual_seed(input.seed)
if input.used_device.type == "cuda" and torch.cuda.is_available():
torch.cuda.manual_seed(input.seed)
torch.cuda.set_device(rank)
dtype = input.dtype
train_dataset = TextAudioLoaderMultiNSFsid(
input.model_files / "filelist.txt", hyperparameters.data
)
train_sampler = DistributedBucketSampler(
train_dataset,
batch_size=input.batch_size * n_gpus,
boundaries=list(map(lambda x: x * 100, range(1, 10))),
num_replicas=n_gpus,
rank=rank,
shuffle=True,
)
collate_fn = TextAudioCollateMultiNSFsid()
train_loader = DataLoader(
train_dataset,
num_workers=optimal_cores,
shuffle=False,
pin_memory=True,
collate_fn=collate_fn,
batch_sampler=train_sampler,
persistent_workers=True,
prefetch_factor=8,
)
G, D = choose_models(input.version, hyperparameters)
net_g = G().to(input.used_device, dtype)
net_d = D().to(input.used_device, dtype)
optim = input.optimizer
lr = input.learning_rate
betas = hyperparameters.train.betas
eps = hyperparameters.train.eps
optimizer_g, can_comp = choose_optimizer(optim, net_g, lr, betas, eps)
optimizer_d, _ = choose_optimizer(optim, net_d, lr, betas, eps)
needs_unscale = True
def step(
opt: OptimizerType,
loss: torch.Tensor,
scaler: Optional[GradScaler],
ema: Optional[S.AveragedModel],
net: torch.nn.Module,
epoch: int,
accumulated: bool = False,
last: bool = False,
):
nonlocal needs_unscale
if input.gradient_accumulation_steps == 1:
opt.zero_grad()
lr = opt.param_groups[0]["lr"]
if scaler is not None and needs_unscale:
scaler.scale(loss).backward()
if accumulated:
try:
scaler.unscale_(opt)
if input.clip_grad > 0:
torch.nn.utils.clip_grad_norm_(
net.parameters(), input.clip_grad, foreach=True
)
scaler.step(opt)
if last:
scaler.update()
except ValueError:
needs_unscale = False
opt.zero_grad()
logger.warning(
"GradScaler failed, disabling for the rest of training."
)
step(opt, loss, scaler, ema, net, epoch, accumulated, last)
else:
if "lomo" in input.optimizer:
opt: Lomo
opt.grad_norm(loss)
opt.fused_backward(loss, lr)
else:
loss.backward()
if accumulated:
if input.clip_grad > 0:
torch.nn.utils.clip_grad_norm_(
net.parameters(), input.clip_grad, foreach=True
)
opt.step()
if input.gradient_accumulation_steps != 1:
opt.zero_grad()
if ema is not None and accumulated and epoch >= input.secondary_start:
ema.update_parameters(net)
# Have to do this here, since can't deepcopy DDP modules.
sec_nets = [None, None]
sec_lr = [None, None]
if input.secondary_model != "none":
logger.info(f"Constructing {input.secondary_model.upper()} models.")
# All this, just to avoid deepcopy...
def create_avg_model(constr, device, multi_avg_fn=None) -> S.AveragedModel:
net: S.AveragedModel = S.AveragedModel.__new__(S.AveragedModel)
torch.nn.Module.__init__(net)
net.module = constr().to(device, dtype)
net.register_buffer(