parent
4b7786f2ed
commit
8db06444c5
@ -0,0 +1,183 @@
|
||||
# This configuration tested on 4 GPUs (V100) with 32GB GPU
|
||||
# memory. It takes around 2 weeks to finish the training
|
||||
# but 100k iters model should generate reasonable results.
|
||||
###########################################################
|
||||
# FEATURE EXTRACTION SETTING #
|
||||
###########################################################
|
||||
|
||||
fs: 22050 # sr
|
||||
n_fft: 1024 # FFT size (samples).
|
||||
n_shift: 256 # Hop size (samples). 12.5ms
|
||||
win_length: null # Window length (samples). 50ms
|
||||
# If set to null, it will be the same as fft_size.
|
||||
window: "hann" # Window function.
|
||||
|
||||
|
||||
##########################################################
|
||||
# TTS MODEL SETTING #
|
||||
##########################################################
|
||||
model:
|
||||
# generator related
|
||||
generator_type: vits_generator
|
||||
generator_params:
|
||||
hidden_channels: 192
|
||||
spks: -1
|
||||
global_channels: -1
|
||||
segment_size: 32
|
||||
text_encoder_attention_heads: 2
|
||||
text_encoder_ffn_expand: 4
|
||||
text_encoder_blocks: 6
|
||||
text_encoder_positionwise_layer_type: "conv1d"
|
||||
text_encoder_positionwise_conv_kernel_size: 3
|
||||
text_encoder_positional_encoding_layer_type: "rel_pos"
|
||||
text_encoder_self_attention_layer_type: "rel_selfattn"
|
||||
text_encoder_activation_type: "swish"
|
||||
text_encoder_normalize_before: True
|
||||
text_encoder_dropout_rate: 0.1
|
||||
text_encoder_positional_dropout_rate: 0.0
|
||||
text_encoder_attention_dropout_rate: 0.1
|
||||
use_macaron_style_in_text_encoder: True
|
||||
use_conformer_conv_in_text_encoder: False
|
||||
text_encoder_conformer_kernel_size: -1
|
||||
decoder_kernel_size: 7
|
||||
decoder_channels: 512
|
||||
decoder_upsample_scales: [8, 8, 2, 2]
|
||||
decoder_upsample_kernel_sizes: [16, 16, 4, 4]
|
||||
decoder_resblock_kernel_sizes: [3, 7, 11]
|
||||
decoder_resblock_dilations: [[1, 3, 5], [1, 3, 5], [1, 3, 5]]
|
||||
use_weight_norm_in_decoder: True
|
||||
posterior_encoder_kernel_size: 5
|
||||
posterior_encoder_layers: 16
|
||||
posterior_encoder_stacks: 1
|
||||
posterior_encoder_base_dilation: 1
|
||||
posterior_encoder_dropout_rate: 0.0
|
||||
use_weight_norm_in_posterior_encoder: True
|
||||
flow_flows: 4
|
||||
flow_kernel_size: 5
|
||||
flow_base_dilation: 1
|
||||
flow_layers: 4
|
||||
flow_dropout_rate: 0.0
|
||||
use_weight_norm_in_flow: True
|
||||
use_only_mean_in_flow: True
|
||||
stochastic_duration_predictor_kernel_size: 3
|
||||
stochastic_duration_predictor_dropout_rate: 0.5
|
||||
stochastic_duration_predictor_flows: 4
|
||||
stochastic_duration_predictor_dds_conv_layers: 3
|
||||
# discriminator related
|
||||
discriminator_type: hifigan_multi_scale_multi_period_discriminator
|
||||
discriminator_params:
|
||||
scales: 1
|
||||
scale_downsample_pooling: "AvgPool1D"
|
||||
scale_downsample_pooling_params:
|
||||
kernel_size: 4
|
||||
stride: 2
|
||||
padding: 2
|
||||
scale_discriminator_params:
|
||||
in_channels: 1
|
||||
out_channels: 1
|
||||
kernel_sizes: [15, 41, 5, 3]
|
||||
channels: 128
|
||||
max_downsample_channels: 1024
|
||||
max_groups: 16
|
||||
bias: True
|
||||
downsample_scales: [2, 2, 4, 4, 1]
|
||||
nonlinear_activation: "leakyrelu"
|
||||
nonlinear_activation_params:
|
||||
negative_slope: 0.1
|
||||
use_weight_norm: True
|
||||
use_spectral_norm: False
|
||||
follow_official_norm: False
|
||||
periods: [2, 3, 5, 7, 11]
|
||||
period_discriminator_params:
|
||||
in_channels: 1
|
||||
out_channels: 1
|
||||
kernel_sizes: [5, 3]
|
||||
channels: 32
|
||||
downsample_scales: [3, 3, 3, 3, 1]
|
||||
max_downsample_channels: 1024
|
||||
bias: True
|
||||
nonlinear_activation: "leakyrelu"
|
||||
nonlinear_activation_params:
|
||||
negative_slope: 0.1
|
||||
use_weight_norm: True
|
||||
use_spectral_norm: False
|
||||
# others
|
||||
sampling_rate: 22050 # needed in the inference for saving wav
|
||||
cache_generator_outputs: True # whether to cache generator outputs in the training
|
||||
|
||||
###########################################################
|
||||
# LOSS SETTING #
|
||||
###########################################################
|
||||
# loss function related
|
||||
generator_adv_loss_params:
|
||||
average_by_discriminators: False # whether to average loss value by #discriminators
|
||||
loss_type: mse # loss type, "mse" or "hinge"
|
||||
discriminator_adv_loss_params:
|
||||
average_by_discriminators: False # whether to average loss value by #discriminators
|
||||
loss_type: mse # loss type, "mse" or "hinge"
|
||||
feat_match_loss_params:
|
||||
average_by_discriminators: False # whether to average loss value by #discriminators
|
||||
average_by_layers: False # whether to average loss value by #layers of each discriminator
|
||||
include_final_outputs: True # whether to include final outputs for loss calculation
|
||||
mel_loss_params:
|
||||
fs: 22050 # must be the same as the training data
|
||||
fft_size: 1024 # fft points
|
||||
hop_size: 256 # hop size
|
||||
win_length: null # window length
|
||||
window: hann # window type
|
||||
num_mels: 80 # number of Mel basis
|
||||
fmin: 0 # minimum frequency for Mel basis
|
||||
fmax: null # maximum frequency for Mel basis
|
||||
log_base: null # null represent natural log
|
||||
|
||||
###########################################################
|
||||
# ADVERSARIAL LOSS SETTING #
|
||||
###########################################################
|
||||
lambda_adv: 1.0 # loss scaling coefficient for adversarial loss
|
||||
lambda_mel: 45.0 # loss scaling coefficient for Mel loss
|
||||
lambda_feat_match: 2.0 # loss scaling coefficient for feat match loss
|
||||
lambda_dur: 1.0 # loss scaling coefficient for duration loss
|
||||
lambda_kl: 1.0 # loss scaling coefficient for KL divergence loss
|
||||
# others
|
||||
sampling_rate: 22050 # needed in the inference for saving wav
|
||||
cache_generator_outputs: True # whether to cache generator outputs in the training
|
||||
|
||||
|
||||
###########################################################
|
||||
# DATA LOADER SETTING #
|
||||
###########################################################
|
||||
batch_size: 64 # Batch size.
|
||||
num_workers: 4 # Number of workers in DataLoader.
|
||||
|
||||
##########################################################
|
||||
# OPTIMIZER & SCHEDULER SETTING #
|
||||
##########################################################
|
||||
# optimizer setting for generator
|
||||
generator_optimizer_params:
|
||||
beta1: 0.8
|
||||
beta2: 0.99
|
||||
epsilon: 1.0e-9
|
||||
weight_decay: 0.0
|
||||
generator_scheduler: exponential_decay
|
||||
generator_scheduler_params:
|
||||
learning_rate: 2.0e-4
|
||||
gamma: 0.999875
|
||||
|
||||
# optimizer setting for discriminator
|
||||
discriminator_optimizer_params:
|
||||
beta1: 0.8
|
||||
beta2: 0.99
|
||||
epsilon: 1.0e-9
|
||||
weight_decay: 0.0
|
||||
discriminator_scheduler: exponential_decay
|
||||
discriminator_scheduler_params:
|
||||
learning_rate: 2.0e-4
|
||||
gamma: 0.999875
|
||||
generator_first: False # whether to start updating generator first
|
||||
|
||||
##########################################################
|
||||
# OTHER TRAINING SETTING #
|
||||
##########################################################
|
||||
max_epoch: 1000 # number of epochs
|
||||
num_snapshots: 10 # max number of snapshots to keep while training
|
||||
seed: 777 # random seed number
|
@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
|
||||
stage=0
|
||||
stop_stage=100
|
||||
|
||||
config_path=$1
|
||||
|
||||
if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then
|
||||
# get durations from MFA's result
|
||||
echo "Generate durations.txt from MFA results ..."
|
||||
python3 ${MAIN_ROOT}/utils/gen_duration_from_textgrid.py \
|
||||
--inputdir=./baker_alignment_tone \
|
||||
--output=durations.txt \
|
||||
--config=${config_path}
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then
|
||||
# extract features
|
||||
echo "Extract features ..."
|
||||
python3 ${BIN_DIR}/preprocess.py \
|
||||
--dataset=baker \
|
||||
--rootdir=~/datasets/BZNSYP/ \
|
||||
--dumpdir=dump \
|
||||
--dur-file=durations.txt \
|
||||
--config=${config_path} \
|
||||
--num-cpu=20 \
|
||||
--cut-sil=True
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then
|
||||
# get features' stats(mean and std)
|
||||
echo "Get features' stats ..."
|
||||
python3 ${MAIN_ROOT}/utils/compute_statistics.py \
|
||||
--metadata=dump/train/raw/metadata.jsonl \
|
||||
--field-name="feats"
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then
|
||||
# normalize and covert phone/speaker to id, dev and test should use train's stats
|
||||
echo "Normalize ..."
|
||||
python3 ${BIN_DIR}/normalize.py \
|
||||
--metadata=dump/train/raw/metadata.jsonl \
|
||||
--dumpdir=dump/train/norm \
|
||||
--feats-stats=dump/train/feats_stats.npy \
|
||||
--phones-dict=dump/phone_id_map.txt \
|
||||
--speaker-dict=dump/speaker_id_map.txt \
|
||||
--skip-wav-copy
|
||||
|
||||
python3 ${BIN_DIR}/normalize.py \
|
||||
--metadata=dump/dev/raw/metadata.jsonl \
|
||||
--dumpdir=dump/dev/norm \
|
||||
--feats-stats=dump/train/feats_stats.npy \
|
||||
--phones-dict=dump/phone_id_map.txt \
|
||||
--speaker-dict=dump/speaker_id_map.txt \
|
||||
--skip-wav-copy
|
||||
|
||||
python3 ${BIN_DIR}/normalize.py \
|
||||
--metadata=dump/test/raw/metadata.jsonl \
|
||||
--dumpdir=dump/test/norm \
|
||||
--feats-stats=dump/train/feats_stats.npy \
|
||||
--phones-dict=dump/phone_id_map.txt \
|
||||
--speaker-dict=dump/speaker_id_map.txt \
|
||||
--skip-wav-copy
|
||||
fi
|
@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
|
||||
config_path=$1
|
||||
train_output_path=$2
|
||||
ckpt_name=$3
|
||||
stage=0
|
||||
stop_stage=0
|
||||
|
||||
if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then
|
||||
FLAGS_allocator_strategy=naive_best_fit \
|
||||
FLAGS_fraction_of_gpu_memory_to_use=0.01 \
|
||||
python3 ${BIN_DIR}/synthesize.py \
|
||||
--config=${config_path} \
|
||||
--ckpt=${train_output_path}/checkpoints/${ckpt_name} \
|
||||
--phones_dict=dump/phone_id_map.txt \
|
||||
--test_metadata=dump/test/norm/metadata.jsonl \
|
||||
--output_dir=${train_output_path}/test
|
||||
fi
|
@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
|
||||
config_path=$1
|
||||
train_output_path=$2
|
||||
ckpt_name=$3
|
||||
stage=0
|
||||
stop_stage=0
|
||||
|
||||
if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then
|
||||
FLAGS_allocator_strategy=naive_best_fit \
|
||||
FLAGS_fraction_of_gpu_memory_to_use=0.01 \
|
||||
python3 ${BIN_DIR}/synthesize_e2e.py \
|
||||
--config=${config_path} \
|
||||
--ckpt=${train_output_path}/checkpoints/${ckpt_name} \
|
||||
--phones_dict=dump/phone_id_map.txt \
|
||||
--output_dir=${train_output_path}/test_e2e \
|
||||
--text=${BIN_DIR}/../sentences.txt
|
||||
fi
|
@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
|
||||
config_path=$1
|
||||
train_output_path=$2
|
||||
|
||||
python3 ${BIN_DIR}/train.py \
|
||||
--train-metadata=dump/train/norm/metadata.jsonl \
|
||||
--dev-metadata=dump/dev/norm/metadata.jsonl \
|
||||
--config=${config_path} \
|
||||
--output-dir=${train_output_path} \
|
||||
--ngpu=4 \
|
||||
--phones-dict=dump/phone_id_map.txt
|
@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
source path.sh
|
||||
|
||||
gpus=0,1
|
||||
stage=0
|
||||
stop_stage=100
|
||||
|
||||
conf_path=conf/default.yaml
|
||||
train_output_path=exp/default
|
||||
ckpt_name=snapshot_iter_153.pdz
|
||||
|
||||
# with the following command, you can choose the stage range you want to run
|
||||
# such as `./run.sh --stage 0 --stop-stage 0`
|
||||
# this can not be mixed use with `$1`, `$2` ...
|
||||
source ${MAIN_ROOT}/utils/parse_options.sh || exit 1
|
||||
|
||||
if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then
|
||||
# prepare data
|
||||
./local/preprocess.sh ${conf_path} || exit -1
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then
|
||||
# train model, all `ckpt` under `train_output_path/checkpoints/` dir
|
||||
CUDA_VISIBLE_DEVICES=${gpus} ./local/train.sh ${conf_path} ${train_output_path} || exit -1
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then
|
||||
CUDA_VISIBLE_DEVICES=${gpus} ./local/synthesize.sh ${conf_path} ${train_output_path} ${ckpt_name} || exit -1
|
||||
fi
|
||||
|
||||
if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then
|
||||
# synthesize_e2e, vocoder is pwgan
|
||||
CUDA_VISIBLE_DEVICES=${gpus} ./local/synthesize_e2e.sh ${conf_path} ${train_output_path} ${ckpt_name} || exit -1
|
||||
fi
|
@ -0,0 +1,146 @@
|
||||
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import paddle
|
||||
import soundfile as sf
|
||||
import yaml
|
||||
from timer import timer
|
||||
from yacs.config import CfgNode
|
||||
|
||||
from paddlespeech.t2s.exps.syn_utils import get_frontend
|
||||
from paddlespeech.t2s.exps.syn_utils import get_sentences
|
||||
from paddlespeech.t2s.models.vits import VITS
|
||||
|
||||
|
||||
def evaluate(args):
|
||||
|
||||
# Init body.
|
||||
with open(args.config) as f:
|
||||
config = CfgNode(yaml.safe_load(f))
|
||||
|
||||
print("========Args========")
|
||||
print(yaml.safe_dump(vars(args)))
|
||||
print("========Config========")
|
||||
print(config)
|
||||
|
||||
sentences = get_sentences(text_file=args.text, lang=args.lang)
|
||||
|
||||
# frontend
|
||||
frontend = get_frontend(lang=args.lang, phones_dict=args.phones_dict)
|
||||
|
||||
with open(args.phones_dict, "r") as f:
|
||||
phn_id = [line.strip().split() for line in f.readlines()]
|
||||
vocab_size = len(phn_id)
|
||||
print("vocab_size:", vocab_size)
|
||||
|
||||
odim = config.n_fft // 2 + 1
|
||||
|
||||
vits = VITS(idim=vocab_size, odim=odim, **config["model"])
|
||||
vits.set_state_dict(paddle.load(args.ckpt)["main_params"])
|
||||
vits.eval()
|
||||
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
merge_sentences = False
|
||||
|
||||
N = 0
|
||||
T = 0
|
||||
for utt_id, sentence in sentences:
|
||||
with timer() as t:
|
||||
if args.lang == 'zh':
|
||||
input_ids = frontend.get_input_ids(
|
||||
sentence, merge_sentences=merge_sentences)
|
||||
phone_ids = input_ids["phone_ids"]
|
||||
elif args.lang == 'en':
|
||||
input_ids = frontend.get_input_ids(
|
||||
sentence, merge_sentences=merge_sentences)
|
||||
phone_ids = input_ids["phone_ids"]
|
||||
else:
|
||||
print("lang should in {'zh', 'en'}!")
|
||||
with paddle.no_grad():
|
||||
flags = 0
|
||||
for i in range(len(phone_ids)):
|
||||
part_phone_ids = phone_ids[i]
|
||||
out = vits.inference(text=part_phone_ids)
|
||||
wav = out["wav"]
|
||||
if flags == 0:
|
||||
wav_all = wav
|
||||
flags = 1
|
||||
else:
|
||||
wav_all = paddle.concat([wav_all, wav])
|
||||
wav = wav_all.numpy()
|
||||
N += wav.size
|
||||
T += t.elapse
|
||||
speed = wav.size / t.elapse
|
||||
rtf = config.fs / speed
|
||||
print(
|
||||
f"{utt_id}, wave: {wav.shape}, time: {t.elapse}s, Hz: {speed}, RTF: {rtf}."
|
||||
)
|
||||
sf.write(str(output_dir / (utt_id + ".wav")), wav, samplerate=config.fs)
|
||||
print(f"{utt_id} done!")
|
||||
print(f"generation speed: {N / T}Hz, RTF: {config.fs / (N / T) }")
|
||||
|
||||
|
||||
def parse_args():
|
||||
# parse args and config
|
||||
parser = argparse.ArgumentParser(description="Synthesize with VITS")
|
||||
|
||||
# model
|
||||
parser.add_argument(
|
||||
'--config', type=str, default=None, help='Config of VITS.')
|
||||
parser.add_argument(
|
||||
'--ckpt', type=str, default=None, help='Checkpoint file of VITS.')
|
||||
parser.add_argument(
|
||||
"--phones_dict", type=str, default=None, help="phone vocabulary file.")
|
||||
# other
|
||||
parser.add_argument(
|
||||
'--lang',
|
||||
type=str,
|
||||
default='zh',
|
||||
help='Choose model language. zh or en')
|
||||
|
||||
parser.add_argument(
|
||||
"--inference_dir",
|
||||
type=str,
|
||||
default=None,
|
||||
help="dir to save inference models")
|
||||
parser.add_argument(
|
||||
"--ngpu", type=int, default=1, help="if ngpu == 0, use cpu.")
|
||||
parser.add_argument(
|
||||
"--text",
|
||||
type=str,
|
||||
help="text to synthesize, a 'utt_id sentence' pair per line.")
|
||||
parser.add_argument("--output_dir", type=str, help="output dir.")
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
|
||||
if args.ngpu == 0:
|
||||
paddle.set_device("cpu")
|
||||
elif args.ngpu > 0:
|
||||
paddle.set_device("gpu")
|
||||
else:
|
||||
print("ngpu should >= 0 !")
|
||||
|
||||
evaluate(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -0,0 +1,353 @@
|
||||
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
import paddle
|
||||
from paddle import distributed as dist
|
||||
from paddle.io import DataLoader
|
||||
from paddle.nn import Layer
|
||||
from paddle.optimizer import Optimizer
|
||||
from paddle.optimizer.lr import LRScheduler
|
||||
|
||||
from paddlespeech.t2s.modules.nets_utils import get_segments
|
||||
from paddlespeech.t2s.training.extensions.evaluator import StandardEvaluator
|
||||
from paddlespeech.t2s.training.reporter import report
|
||||
from paddlespeech.t2s.training.updaters.standard_updater import StandardUpdater
|
||||
from paddlespeech.t2s.training.updaters.standard_updater import UpdaterState
|
||||
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
|
||||
datefmt='[%Y-%m-%d %H:%M:%S]')
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
class VITSUpdater(StandardUpdater):
|
||||
def __init__(self,
|
||||
model: Layer,
|
||||
optimizers: Dict[str, Optimizer],
|
||||
criterions: Dict[str, Layer],
|
||||
schedulers: Dict[str, LRScheduler],
|
||||
dataloader: DataLoader,
|
||||
generator_train_start_steps: int=0,
|
||||
discriminator_train_start_steps: int=100000,
|
||||
lambda_adv: float=1.0,
|
||||
lambda_mel: float=45.0,
|
||||
lambda_feat_match: float=2.0,
|
||||
lambda_dur: float=1.0,
|
||||
lambda_kl: float=1.0,
|
||||
generator_first: bool=False,
|
||||
output_dir=None):
|
||||
# it is designed to hold multiple models
|
||||
# 因为输入的是单模型,但是没有用到父类的 init(), 所以需要重新写这部分
|
||||
models = {"main": model}
|
||||
self.models: Dict[str, Layer] = models
|
||||
# self.model = model
|
||||
|
||||
self.model = model._layers if isinstance(model, paddle.DataParallel) else model
|
||||
|
||||
self.optimizers = optimizers
|
||||
self.optimizer_g: Optimizer = optimizers['generator']
|
||||
self.optimizer_d: Optimizer = optimizers['discriminator']
|
||||
|
||||
self.criterions = criterions
|
||||
self.criterion_mel = criterions['mel']
|
||||
self.criterion_feat_match = criterions['feat_match']
|
||||
self.criterion_gen_adv = criterions["gen_adv"]
|
||||
self.criterion_dis_adv = criterions["dis_adv"]
|
||||
self.criterion_kl = criterions["kl"]
|
||||
|
||||
self.schedulers = schedulers
|
||||
self.scheduler_g = schedulers['generator']
|
||||
self.scheduler_d = schedulers['discriminator']
|
||||
|
||||
self.dataloader = dataloader
|
||||
|
||||
self.generator_train_start_steps = generator_train_start_steps
|
||||
self.discriminator_train_start_steps = discriminator_train_start_steps
|
||||
|
||||
self.lambda_adv = lambda_adv
|
||||
self.lambda_mel = lambda_mel
|
||||
self.lambda_feat_match = lambda_feat_match
|
||||
self.lambda_dur = lambda_dur
|
||||
self.lambda_kl = lambda_kl
|
||||
|
||||
if generator_first:
|
||||
self.turns = ["generator", "discriminator"]
|
||||
else:
|
||||
self.turns = ["discriminator", "generator"]
|
||||
|
||||
self.state = UpdaterState(iteration=0, epoch=0)
|
||||
self.train_iterator = iter(self.dataloader)
|
||||
|
||||
log_file = output_dir / 'worker_{}.log'.format(dist.get_rank())
|
||||
self.filehandler = logging.FileHandler(str(log_file))
|
||||
logger.addHandler(self.filehandler)
|
||||
self.logger = logger
|
||||
self.msg = ""
|
||||
|
||||
def update_core(self, batch):
|
||||
self.msg = "Rank: {}, ".format(dist.get_rank())
|
||||
losses_dict = {}
|
||||
|
||||
for turn in self.turns:
|
||||
speech = batch["speech"]
|
||||
speech = speech.unsqueeze(1)
|
||||
outs = self.model(
|
||||
text=batch["text"],
|
||||
text_lengths=batch["text_lengths"],
|
||||
feats=batch["feats"],
|
||||
feats_lengths=batch["feats_lengths"],
|
||||
forward_generator=turn == "generator")
|
||||
# Generator
|
||||
if turn == "generator":
|
||||
# parse outputs
|
||||
speech_hat_, dur_nll, _, start_idxs, _, z_mask, outs_ = outs
|
||||
_, z_p, m_p, logs_p, _, logs_q = outs_
|
||||
speech_ = get_segments(
|
||||
x=speech,
|
||||
start_idxs=start_idxs *
|
||||
self.model.generator.upsample_factor,
|
||||
segment_size=self.model.generator.segment_size *
|
||||
self.model.generator.upsample_factor, )
|
||||
|
||||
# calculate discriminator outputs
|
||||
p_hat = self.model.discriminator(speech_hat_)
|
||||
with paddle.no_grad():
|
||||
# do not store discriminator gradient in generator turn
|
||||
p = self.model.discriminator(speech_)
|
||||
|
||||
# calculate losses
|
||||
mel_loss = self.criterion_mel(speech_hat_, speech_)
|
||||
kl_loss = self.criterion_kl(z_p, logs_q, m_p, logs_p, z_mask)
|
||||
dur_loss = paddle.sum(dur_nll)
|
||||
adv_loss = self.criterion_gen_adv(p_hat)
|
||||
feat_match_loss = self.criterion_feat_match(p_hat, p)
|
||||
|
||||
mel_loss = mel_loss * self.lambda_mel
|
||||
kl_loss = kl_loss * self.lambda_kl
|
||||
dur_loss = dur_loss * self.lambda_dur
|
||||
adv_loss = adv_loss * self.lambda_adv
|
||||
feat_match_loss = feat_match_loss * self.lambda_feat_match
|
||||
gen_loss = mel_loss + kl_loss + dur_loss + adv_loss + feat_match_loss
|
||||
|
||||
report("train/generator_loss", float(gen_loss))
|
||||
report("train/generator_mel_loss", float(mel_loss))
|
||||
report("train/generator_kl_loss", float(kl_loss))
|
||||
report("train/generator_dur_loss", float(dur_loss))
|
||||
report("train/generator_adv_loss", float(adv_loss))
|
||||
report("train/generator_feat_match_loss",
|
||||
float(feat_match_loss))
|
||||
|
||||
losses_dict["generator_loss"] = float(gen_loss)
|
||||
losses_dict["generator_mel_loss"] = float(mel_loss)
|
||||
losses_dict["generator_kl_loss"] = float(kl_loss)
|
||||
losses_dict["generator_dur_loss"] = float(dur_loss)
|
||||
losses_dict["generator_adv_loss"] = float(adv_loss)
|
||||
losses_dict["generator_feat_match_loss"] = float(
|
||||
feat_match_loss)
|
||||
|
||||
self.optimizer_g.clear_grad()
|
||||
gen_loss.backward()
|
||||
|
||||
self.optimizer_g.step()
|
||||
self.scheduler_g.step()
|
||||
|
||||
# reset cache
|
||||
if self.model.reuse_cache_gen or not self.model.training:
|
||||
self.model._cache = None
|
||||
|
||||
# Disctiminator
|
||||
elif turn == "discriminator":
|
||||
# parse outputs
|
||||
speech_hat_, _, _, start_idxs, *_ = outs
|
||||
speech_ = get_segments(
|
||||
x=speech,
|
||||
start_idxs=start_idxs *
|
||||
self.model.generator.upsample_factor,
|
||||
segment_size=self.model.generator.segment_size *
|
||||
self.model.generator.upsample_factor, )
|
||||
|
||||
# calculate discriminator outputs
|
||||
p_hat = self.model.discriminator(speech_hat_.detach())
|
||||
p = self.model.discriminator(speech_)
|
||||
|
||||
# calculate losses
|
||||
real_loss, fake_loss = self.criterion_dis_adv(p_hat, p)
|
||||
dis_loss = real_loss + fake_loss
|
||||
|
||||
report("train/real_loss", float(real_loss))
|
||||
report("train/fake_loss", float(fake_loss))
|
||||
report("train/discriminator_loss", float(dis_loss))
|
||||
losses_dict["real_loss"] = float(real_loss)
|
||||
losses_dict["fake_loss"] = float(fake_loss)
|
||||
losses_dict["discriminator_loss"] = float(dis_loss)
|
||||
|
||||
self.optimizer_d.clear_grad()
|
||||
dis_loss.backward()
|
||||
|
||||
self.optimizer_d.step()
|
||||
self.scheduler_d.step()
|
||||
|
||||
# reset cache
|
||||
if self.model.reuse_cache_dis or not self.model.training:
|
||||
self.model._cache = None
|
||||
|
||||
self.msg += ', '.join('{}: {:>.6f}'.format(k, v)
|
||||
for k, v in losses_dict.items())
|
||||
|
||||
|
||||
class VITSEvaluator(StandardEvaluator):
|
||||
def __init__(self,
|
||||
model,
|
||||
criterions: Dict[str, Layer],
|
||||
dataloader: DataLoader,
|
||||
lambda_adv: float=1.0,
|
||||
lambda_mel: float=45.0,
|
||||
lambda_feat_match: float=2.0,
|
||||
lambda_dur: float=1.0,
|
||||
lambda_kl: float=1.0,
|
||||
generator_first: bool=False,
|
||||
output_dir=None):
|
||||
# 因为输入的是单模型,但是没有用到父类的 init(), 所以需要重新写这部分
|
||||
models = {"main": model}
|
||||
self.models: Dict[str, Layer] = models
|
||||
# self.model = model
|
||||
self.model = model._layers if isinstance(model, paddle.DataParallel) else model
|
||||
|
||||
self.criterions = criterions
|
||||
self.criterion_mel = criterions['mel']
|
||||
self.criterion_feat_match = criterions['feat_match']
|
||||
self.criterion_gen_adv = criterions["gen_adv"]
|
||||
self.criterion_dis_adv = criterions["dis_adv"]
|
||||
self.criterion_kl = criterions["kl"]
|
||||
|
||||
self.dataloader = dataloader
|
||||
|
||||
self.lambda_adv = lambda_adv
|
||||
self.lambda_mel = lambda_mel
|
||||
self.lambda_feat_match = lambda_feat_match
|
||||
self.lambda_dur = lambda_dur
|
||||
self.lambda_kl = lambda_kl
|
||||
|
||||
if generator_first:
|
||||
self.turns = ["generator", "discriminator"]
|
||||
else:
|
||||
self.turns = ["discriminator", "generator"]
|
||||
|
||||
log_file = output_dir / 'worker_{}.log'.format(dist.get_rank())
|
||||
self.filehandler = logging.FileHandler(str(log_file))
|
||||
logger.addHandler(self.filehandler)
|
||||
self.logger = logger
|
||||
self.msg = ""
|
||||
|
||||
def evaluate_core(self, batch):
|
||||
# logging.debug("Evaluate: ")
|
||||
self.msg = "Evaluate: "
|
||||
losses_dict = {}
|
||||
|
||||
for turn in self.turns:
|
||||
speech = batch["speech"]
|
||||
speech = speech.unsqueeze(1)
|
||||
outs = self.model(
|
||||
text=batch["text"],
|
||||
text_lengths=batch["text_lengths"],
|
||||
feats=batch["feats"],
|
||||
feats_lengths=batch["feats_lengths"],
|
||||
forward_generator=turn == "generator")
|
||||
# Generator
|
||||
if turn == "generator":
|
||||
# parse outputs
|
||||
speech_hat_, dur_nll, _, start_idxs, _, z_mask, outs_ = outs
|
||||
_, z_p, m_p, logs_p, _, logs_q = outs_
|
||||
speech_ = get_segments(
|
||||
x=speech,
|
||||
start_idxs=start_idxs *
|
||||
self.model.generator.upsample_factor,
|
||||
segment_size=self.model.generator.segment_size *
|
||||
self.model.generator.upsample_factor, )
|
||||
|
||||
# calculate discriminator outputs
|
||||
p_hat = self.model.discriminator(speech_hat_)
|
||||
with paddle.no_grad():
|
||||
# do not store discriminator gradient in generator turn
|
||||
p = self.model.discriminator(speech_)
|
||||
|
||||
# calculate losses
|
||||
mel_loss = self.criterion_mel(speech_hat_, speech_)
|
||||
kl_loss = self.criterion_kl(z_p, logs_q, m_p, logs_p, z_mask)
|
||||
dur_loss = paddle.sum(dur_nll)
|
||||
adv_loss = self.criterion_gen_adv(p_hat)
|
||||
feat_match_loss = self.criterion_feat_match(p_hat, p)
|
||||
|
||||
mel_loss = mel_loss * self.lambda_mel
|
||||
kl_loss = kl_loss * self.lambda_kl
|
||||
dur_loss = dur_loss * self.lambda_dur
|
||||
adv_loss = adv_loss * self.lambda_adv
|
||||
feat_match_loss = feat_match_loss * self.lambda_feat_match
|
||||
gen_loss = mel_loss + kl_loss + dur_loss + adv_loss + feat_match_loss
|
||||
|
||||
report("eval/generator_loss", float(gen_loss))
|
||||
report("eval/generator_mel_loss", float(mel_loss))
|
||||
report("eval/generator_kl_loss", float(kl_loss))
|
||||
report("eval/generator_dur_loss", float(dur_loss))
|
||||
report("eval/generator_adv_loss", float(adv_loss))
|
||||
report("eval/generator_feat_match_loss", float(feat_match_loss))
|
||||
|
||||
losses_dict["generator_loss"] = float(gen_loss)
|
||||
losses_dict["generator_mel_loss"] = float(mel_loss)
|
||||
losses_dict["generator_kl_loss"] = float(kl_loss)
|
||||
losses_dict["generator_dur_loss"] = float(dur_loss)
|
||||
losses_dict["generator_adv_loss"] = float(adv_loss)
|
||||
losses_dict["generator_feat_match_loss"] = float(
|
||||
feat_match_loss)
|
||||
|
||||
# reset cache
|
||||
if self.model.reuse_cache_gen or not self.model.training:
|
||||
self.model._cache = None
|
||||
|
||||
# Disctiminator
|
||||
elif turn == "discriminator":
|
||||
# parse outputs
|
||||
speech_hat_, _, _, start_idxs, *_ = outs
|
||||
speech_ = get_segments(
|
||||
x=speech,
|
||||
start_idxs=start_idxs *
|
||||
self.model.generator.upsample_factor,
|
||||
segment_size=self.model.generator.segment_size *
|
||||
self.model.generator.upsample_factor, )
|
||||
|
||||
# calculate discriminator outputs
|
||||
p_hat = self.model.discriminator(speech_hat_.detach())
|
||||
p = self.model.discriminator(speech_)
|
||||
|
||||
# calculate losses
|
||||
real_loss, fake_loss = self.criterion_dis_adv(p_hat, p)
|
||||
dis_loss = real_loss + fake_loss
|
||||
|
||||
report("eval/real_loss", float(real_loss))
|
||||
report("eval/fake_loss", float(fake_loss))
|
||||
report("eval/discriminator_loss", float(dis_loss))
|
||||
losses_dict["real_loss"] = float(real_loss)
|
||||
losses_dict["fake_loss"] = float(fake_loss)
|
||||
losses_dict["discriminator_loss"] = float(dis_loss)
|
||||
|
||||
# reset cache
|
||||
if self.model.reuse_cache_dis or not self.model.training:
|
||||
self.model._cache = None
|
||||
|
||||
self.msg += ', '.join('{}: {:>.6f}'.format(k, v)
|
||||
for k, v in losses_dict.items())
|
||||
self.logger.info(self.msg)
|
@ -0,0 +1,13 @@
|
||||
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
@ -0,0 +1,38 @@
|
||||
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# Modified from espnet(https://github.com/espnet/espnet)
|
||||
import importlib
|
||||
|
||||
__all__ = ["dynamic_import"]
|
||||
|
||||
|
||||
def dynamic_import(import_path, alias=dict()):
|
||||
"""dynamic import module and class
|
||||
|
||||
:param str import_path: syntax 'module_name:class_name'
|
||||
e.g., 'paddlespeech.s2t.models.u2:U2Model'
|
||||
:param dict alias: shortcut for registered class
|
||||
:return: imported class
|
||||
"""
|
||||
if import_path not in alias and ":" not in import_path:
|
||||
raise ValueError(
|
||||
"import_path should be one of {} or "
|
||||
'include ":", e.g. "paddlespeech.s2t.models.u2:U2Model" : '
|
||||
"{}".format(set(alias), import_path))
|
||||
if ":" not in import_path:
|
||||
import_path = alias[import_path]
|
||||
|
||||
module_name, objname = import_path.split(":")
|
||||
m = importlib.import_module(module_name)
|
||||
return getattr(m, objname)
|
Loading…
Reference in new issue