这部分主要是按照模型一个模型具体的训练过程展开的,主要是按照如下步骤
但是实际上作者在训练的过程中,并不是严格按照这个步骤进行更新的,他是先训练了鉴定器,然后在训练生成器的过程中又重新对鉴定器进行了一次前向传播,使用鉴定器的结果输出,来反向传播影响生成器的权重.
# 创建生成器和鉴定器,并将之放置在设备上
generator = Generator(h).to(device)
mpd = MultiPeriodDiscriminator().to(device)
msd = MultiScaleDiscriminator().to(device)
optim_g = torch.optim.AdamW(generator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2])
# 注意这里,判别器的优化器会影响多尺度判别器MSD和多周期判别器MPD
optim_d = torch.optim.AdamW(itertools.chain(msd.parameters(), mpd.parameters()),h.learning_rate, betas=[h.adam_b1, h.adam_b2])
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=h.lr_decay, last_epoch=last_epoch)
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=h.lr_decay, last_epoch=last_epoch)
# 获取训练文件的列表
training_filelist, validation_filelist = get_dataset_filelist(a)
# 将音频文件转为mel频谱图
trainset = MelDataset(training_filelist, h.segment_size, h.n_fft, h.num_mels,
h.hop_size, h.win_size, h.sampling_rate, h.fmin, h.fmax, n_cache_reuse=0,
shuffle=False if h.num_gpus > 1 else True, fmax_loss=h.fmax_for_loss, device=device,
fine_tuning=a.fine_tuning, base_mels_path=a.input_mels_dir)
# 创建DataLoader数据加载对象
train_loader = DataLoader(trainset, num_workers=h.num_workers, shuffle=False,
sampler=train_sampler,
batch_size=h.batch_size,
pin_memory=True,
drop_last=True)
# 创建验证集的数据加载对象
validset = MelDataset(validation_filelist, h.segment_size, h.n_fft, h.num_mels,
h.hop_size, h.win_size, h.sampling_rate, h.fmin, h.fmax, False, False, n_cache_reuse=0,
fmax_loss=h.fmax_for_loss, device=device, fine_tuning=a.fine_tuning,
base_mels_path=a.input_mels_dir)
validation_loader = DataLoader(validset, num_workers=1, shuffle=False,
sampler=None,
batch_size=1,
pin_memory=True,
drop_last=True)
# 设置模型为训练模式
generator.train()
mpd.train()
msd.train()
# 遍历数据批次
for i, batch in enumerate(train_loader):
# 判定是否为主线程
if rank == 0:
start_b = time.time()
# 从当前的批次中获取输入数据x,目标输出y,以及梅尔频谱图y_mel
x, y, _, y_mel = batch
# 将所有的数据封装为pytorch的变量Variable对象,并将之移动到指定的设备上
x = torch.autograd.Variable(x.to(device, non_blocking=True))
y = torch.autograd.Variable(y.to(device, non_blocking=True))
y_mel = torch.autograd.Variable(y_mel.to(device, non_blocking=True))
# 调整目标输出的维度,增加了目标输出y的维度,确保y和模型的输出y_hat的维度一致
y = y.unsqueeze(1)
# 判别器梯度清零
optim_d.zero_grad()
# Generator
# 生成器梯度清零
optim_g.zero_grad()
# 生成器生成结果
y_g_hat = generator(x)
# 多周期判别器生成结果
y_df_hat_r, y_df_hat_g, _, _ = mpd(y, y_g_hat.detach())
# 多尺度判别器生成结果
y_ds_hat_r, y_ds_hat_g, _, _ = msd(y, y_g_hat.detach())
# 将生成器的生成的波形图y_g_hat生成为对应mel频谱图
y_g_hat_mel = mel_spectrogram(y_g_hat.squeeze(1), h.n_fft, h.num_mels, h.sampling_rate, h.hop_size, h.win_size,h.fmin, h.fmax_for_loss)
# L1 Mel-Spectrogram Loss
# 生成器的L1损失
loss_mel = F.l1_loss(y_mel, y_g_hat_mel) * 45
# 计算两个判别器的损失
# loss_disc_f是多周期判别器的损失
# loss_disc_s是多尺度判别器的损失
# losses_disc_f_r, losses_disc_f_g分别是每一层的多周期鉴定器对于真实数据和生成数据判别结果
# losses_disc_s_r, losses_disc_s_g 分别是每一层的多尺度鉴定器对于真实数据和生成数据判别结果
loss_disc_f, losses_disc_f_r, losses_disc_f_g = discriminator_loss(y_df_hat_r, y_df_hat_g)
loss_disc_s, losses_disc_s_r, losses_disc_s_g = discriminator_loss(y_ds_hat_r, y_ds_hat_g)
loss_disc_all = loss_disc_s + loss_disc_f
# 计算生成器损失,包括mel频谱图的L1损失\特征匹配损失和生成器损失
y_df_hat_r, y_df_hat_g, fmap_f_r, fmap_f_g = mpd(y, y_g_hat)
y_ds_hat_r, y_ds_hat_g, fmap_s_r, fmap_s_g = msd(y, y_g_hat)
loss_fm_f = feature_loss(fmap_f_r, fmap_f_g)
loss_fm_s = feature_loss(fmap_s_r, fmap_s_g)
loss_gen_f, losses_gen_f = generator_loss(y_df_hat_g)
loss_gen_s, losses_gen_s = generator_loss(y_ds_hat_g)
loss_gen_all = loss_gen_s + loss_gen_f + loss_fm_s + loss_fm_f + loss_mel
注意:
10 反向传播和梯度更新
# 反向传播鉴别器的损失
loss_disc_all.backward()
# 梯度更新
optim_d.step()
# 反向传播生成器的损失
loss_gen_all.backward()
# 执行梯度优化
optim_g.step()
# 更新学习率调度器
scheduler_g.step()
scheduler_d.step()
在这个项目的代码中,写了多个GPU同时训练的代码,这里并不是重点,但是还是用来学习使用一下.
1 使用多线进程进行训练
import torch.multiprocessing as mp
def train(rank):
# 训练模型的代码
if __name__ == '__main__':
mp.spawn(train, nprocs=num_gpus)
if h.num_gpus > 1:
generator = DistributedDataParallel(generator, device_ids=[rank]).to(device)
mpd = DistributedDataParallel(mpd, device_ids=[rank]).to(device)
msd = DistributedDataParallel(msd, device_ids=[rank]).to(device)
3 多进程中的进程编号和分类
到此为止吧,这里暂时不做过多的解释,他的代码直接可以使用,因为那个代码包含了多GPU和单GPU训练的代码, 是兼容的.可以直接使用.
def main():
print('Initializing Training Process..')
parser = argparse.ArgumentParser()
# 加载并解析参数
# group_name表示分组名称
parser.add_argument('--group_name', default=None)
# input_wavs_dir表示输入的音频文件夹
parser.add_argument('--input_wavs_dir', default='LJSpeech-1.1/wavs')
# input_mels_dir表示输入的mel谱文件夹
parser.add_argument('--input_mels_dir', default='ft_dataset')
# input_training_file表示输入的训练文件
parser.add_argument('--input_training_file', default='LJSpeech-1.1/training.txt')
# input_validation_file表示输入的验证文件
parser.add_argument('--input_validation_file', default='LJSpeech-1.1/validation.txt')
# checkpoint_path表示检查点路径
parser.add_argument('--checkpoint_path', default='cp_hifigan')
# config表示配置文件
parser.add_argument('--config', default='')
# training_epoches训练的总周期数。默认值为3100。
parser.add_argument('--training_epochs', default=3100, type=int)
# stdout_interval: 标准输出日志的间隔步数。默认值为5。
parser.add_argument('--stdout_interval', default=5, type=int)
# checkpoint_interval: 检查点保存的间隔步数。默认值为5000。
parser.add_argument('--checkpoint_interval', default=5000, type=int)
# summary_interval: TensorBoard摘要记录的间隔步数。默认值为100。
parser.add_argument('--summary_interval', default=100, type=int)
# validation_interval: 验证的间隔步数。默认值为1000。
parser.add_argument('--validation_interval', default=1000, type=int)
# fine_tuning: 是否进行微调。默认值为False。
parser.add_argument('--fine_tuning', default=False, type=bool)
a = parser.parse_args()
# 读取配置文件
with open(a.config) as f:
data = f.read()
# 解析json文件
json_config = json.loads(data)
# 将json文件转换为字典
h = AttrDict(json_config)
# 根据配置文件创建对应文件
build_env(a.config, 'config.json', a.checkpoint_path)
# 设置随机种子,确保训练的可重复性
torch.manual_seed(h.seed)
# 检测GPU,如果多个GPU就同时训练
if torch.cuda.is_available():
torch.cuda.manual_seed(h.seed)
h.num_gpus = torch.cuda.device_count()
h.batch_size = int(h.batch_size / h.num_gpus)
print('Batch size per GPU :', h.batch_size)
else:
pass
if h.num_gpus > 1:
# 多个GPU的训练方式
mp.spawn(train, nprocs=h.num_gpus, args=(a, h,))
else:
# 一个GPU的训练方式
train(0, a, h)
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import itertools
import os
import time
import argparse
import json
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DistributedSampler, DataLoader
import torch.multiprocessing as mp
from torch.distributed import init_process_group
from torch.nn.parallel import DistributedDataParallel
from env import AttrDict, build_env
from meldataset import MelDataset, mel_spectrogram, get_dataset_filelist
from models import Generator, MultiPeriodDiscriminator, MultiScaleDiscriminator, feature_loss, generator_loss,\
discriminator_loss
from utils import plot_spectrogram, scan_checkpoint, load_checkpoint, save_checkpoint
torch.backends.cudnn.benchmark = True
def train(rank, a, h):
# 基本步骤:多个GPU,则初始化分布训练组
if h.num_gpus > 1:
init_process_group(backend=h.dist_config['dist_backend'], init_method=h.dist_config['dist_url'],
world_size=h.dist_config['world_size'] * h.num_gpus, rank=rank)
# 基本步骤:初始化随机种子
torch.cuda.manual_seed(h.seed)
# 基本步骤:设备命名
device = torch.device('cuda:{:d}'.format(rank))
# 创建生成器和鉴定器,并将之放置在设备上
generator = Generator(h).to(device)
mpd = MultiPeriodDiscriminator().to(device)
msd = MultiScaleDiscriminator().to(device)
# 如果是主进程,就打印生成器并且创建检查点目录
if rank == 0:
print(generator)
os.makedirs(a.checkpoint_path, exist_ok=True)
print("checkpoints directory : ", a.checkpoint_path)
# 检查是否存在检查点,如果存在则加载检查点??
# 这里的加载检查点是什么意思??
if os.path.isdir(a.checkpoint_path):
cp_g = scan_checkpoint(a.checkpoint_path, 'g_')
cp_do = scan_checkpoint(a.checkpoint_path, 'do_')
steps = 0
if cp_g is None or cp_do is None:
state_dict_do = None
last_epoch = -1
else:
state_dict_g = load_checkpoint(cp_g, device)
state_dict_do = load_checkpoint(cp_do, device)
generator.load_state_dict(state_dict_g['generator'])
mpd.load_state_dict(state_dict_do['mpd'])
msd.load_state_dict(state_dict_do['msd'])
steps = state_dict_do['steps'] + 1
last_epoch = state_dict_do['epoch']
# 如果有多个GPU,就是用分布式数据并行
if h.num_gpus > 1:
generator = DistributedDataParallel(generator, device_ids=[rank]).to(device)
mpd = DistributedDataParallel(mpd, device_ids=[rank]).to(device)
msd = DistributedDataParallel(msd, device_ids=[rank]).to(device)
# 定义优化器
optim_g = torch.optim.AdamW(generator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2])
optim_d = torch.optim.AdamW(itertools.chain(msd.parameters(), mpd.parameters()),
h.learning_rate, betas=[h.adam_b1, h.adam_b2])
# 如果存在检查点,就加载优化器的状态
if state_dict_do is not None:
optim_g.load_state_dict(state_dict_do['optim_g'])
optim_d.load_state_dict(state_dict_do['optim_d'])
# 定义学习率调度器
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=h.lr_decay, last_epoch=last_epoch)
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=h.lr_decay, last_epoch=last_epoch)
training_filelist, validation_filelist = get_dataset_filelist(a)
trainset = MelDataset(training_filelist, h.segment_size, h.n_fft, h.num_mels,
h.hop_size, h.win_size, h.sampling_rate, h.fmin, h.fmax, n_cache_reuse=0,
shuffle=False if h.num_gpus > 1 else True, fmax_loss=h.fmax_for_loss, device=device,
fine_tuning=a.fine_tuning, base_mels_path=a.input_mels_dir)
# 创建分布式采样器
train_sampler = DistributedSampler(trainset) if h.num_gpus > 1 else None
train_loader = DataLoader(trainset, num_workers=h.num_workers, shuffle=False,
sampler=train_sampler,
batch_size=h.batch_size,
pin_memory=True,
drop_last=True)
if rank == 0:
validset = MelDataset(validation_filelist, h.segment_size, h.n_fft, h.num_mels,
h.hop_size, h.win_size, h.sampling_rate, h.fmin, h.fmax, False, False, n_cache_reuse=0,
fmax_loss=h.fmax_for_loss, device=device, fine_tuning=a.fine_tuning,
base_mels_path=a.input_mels_dir)
validation_loader = DataLoader(validset, num_workers=1, shuffle=False,
sampler=None,
batch_size=1,
pin_memory=True,
drop_last=True)
sw = SummaryWriter(os.path.join(a.checkpoint_path, 'logs'))
# 设置模型为训练模式
generator.train()
mpd.train()
msd.train()
# 开始训练循环
for epoch in range(max(0, last_epoch), a.training_epochs):
if rank == 0:
start = time.time()
print("Epoch: {}".format(epoch+1))
# 如果有多个GPU,就设置分布式数据并行的采样器
if h.num_gpus > 1:
train_sampler.set_epoch(epoch)
# 遍历数据批次
for i, batch in enumerate(train_loader):
if rank == 0:
start_b = time.time()
# 从当前的批次中获取输入数据x,目标输出y,以及梅尔频谱图y_mel
x, y, _, y_mel = batch
# 将所有的数据封装为pytorch的变量Variable对象,并将之移动到指定的设备上
x = torch.autograd.Variable(x.to(device, non_blocking=True))
y = torch.autograd.Variable(y.to(device, non_blocking=True))
y_mel = torch.autograd.Variable(y_mel.to(device, non_blocking=True))
# 调整目标输出的维度,增加了目标输出y的维度,确保y和模型的输出y_hat的维度一致
y = y.unsqueeze(1)
# 生成器生成
y_g_hat = generator(x)
y_g_hat_mel = mel_spectrogram(y_g_hat.squeeze(1), h.n_fft, h.num_mels, h.sampling_rate, h.hop_size, h.win_size,
h.fmin, h.fmax_for_loss)
# 判别器梯度清零
optim_d.zero_grad()
# MPD
# 多周期判别器的损失
y_df_hat_r, y_df_hat_g, _, _ = mpd(y, y_g_hat.detach())
loss_disc_f, losses_disc_f_r, losses_disc_f_g = discriminator_loss(y_df_hat_r, y_df_hat_g)
# MSD
# 多尺度判别器生成的数据
y_ds_hat_r, y_ds_hat_g, _, _ = msd(y, y_g_hat.detach())
loss_disc_s, losses_disc_s_r, losses_disc_s_g = discriminator_loss(y_ds_hat_r, y_ds_hat_g)
# 总的判别器损失
loss_disc_all = loss_disc_s + loss_disc_f
# 反向传播鉴别器的损失
loss_disc_all.backward()
optim_d.step()
# Generator
# 生成器梯度清零
optim_g.zero_grad()
# L1 Mel-Spectrogram Loss
# 生成器的L1损失
loss_mel = F.l1_loss(y_mel, y_g_hat_mel) * 45
# 计算生成器损失,包括mel频谱图的L1损失\特征匹配损失和生成器损失
y_df_hat_r, y_df_hat_g, fmap_f_r, fmap_f_g = mpd(y, y_g_hat)
y_ds_hat_r, y_ds_hat_g, fmap_s_r, fmap_s_g = msd(y, y_g_hat)
loss_fm_f = feature_loss(fmap_f_r, fmap_f_g)
loss_fm_s = feature_loss(fmap_s_r, fmap_s_g)
loss_gen_f, losses_gen_f = generator_loss(y_df_hat_g)
loss_gen_s, losses_gen_s = generator_loss(y_ds_hat_g)
loss_gen_all = loss_gen_s + loss_gen_f + loss_fm_s + loss_fm_f + loss_mel
# 反向传播生成器的损失
loss_gen_all.backward()
# 执行梯度优化
optim_g.step()
# 如果是主进程,进行日志记录 检查点保存和验证
if rank == 0:
# STDOUT logging
# 标准输出日志
if steps % a.stdout_interval == 0:
with torch.no_grad():
mel_error = F.l1_loss(y_mel, y_g_hat_mel).item()
print('Steps : {:d}, Gen Loss Total : {:4.3f}, Mel-Spec. Error : {:4.3f}, s/b : {:4.3f}'.
format(steps, loss_gen_all, mel_error, time.time() - start_b))
# checkpointing
# 检查点保存
if steps % a.checkpoint_interval == 0 and steps != 0:
checkpoint_path = "{}/g_{:08d}".format(a.checkpoint_path, steps)
save_checkpoint(checkpoint_path,
{'generator': (generator.module if h.num_gpus > 1 else generator).state_dict()})
checkpoint_path = "{}/do_{:08d}".format(a.checkpoint_path, steps)
save_checkpoint(checkpoint_path,
{'mpd': (mpd.module if h.num_gpus > 1
else mpd).state_dict(),
'msd': (msd.module if h.num_gpus > 1
else msd).state_dict(),
'optim_g': optim_g.state_dict(), 'optim_d': optim_d.state_dict(), 'steps': steps,
'epoch': epoch})
# Tensorboard summary logging
# tensorboard摘要日志
if steps % a.summary_interval == 0:
sw.add_scalar("training/gen_loss_total", loss_gen_all, steps)
sw.add_scalar("training/mel_spec_error", mel_error, steps)
# Validation
# 验证
if steps % a.validation_interval == 0: # and steps != 0:
generator.eval()
torch.cuda.empty_cache()
val_err_tot = 0
with torch.no_grad():
for j, batch in enumerate(validation_loader):
x, y, _, y_mel = batch
y_g_hat = generator(x.to(device))
y_mel = torch.autograd.Variable(y_mel.to(device, non_blocking=True))
y_g_hat_mel = mel_spectrogram(y_g_hat.squeeze(1), h.n_fft, h.num_mels, h.sampling_rate,
h.hop_size, h.win_size,
h.fmin, h.fmax_for_loss)
val_err_tot += F.l1_loss(y_mel, y_g_hat_mel).item()
# 保存音频和频谱图
if j <= 4:
if steps == 0:
sw.add_audio('gt/y_{}'.format(j), y[0], steps, h.sampling_rate)
sw.add_figure('gt/y_spec_{}'.format(j), plot_spectrogram(x[0]), steps)
sw.add_audio('generated/y_hat_{}'.format(j), y_g_hat[0], steps, h.sampling_rate)
y_hat_spec = mel_spectrogram(y_g_hat.squeeze(1), h.n_fft, h.num_mels,
h.sampling_rate, h.hop_size, h.win_size,
h.fmin, h.fmax)
sw.add_figure('generated/y_hat_spec_{}'.format(j),
plot_spectrogram(y_hat_spec.squeeze(0).cpu().numpy()), steps)
val_err = val_err_tot / (j+1)
sw.add_scalar("validation/mel_spec_error", val_err, steps)
generator.train()
steps += 1
# 更新学习率调度器
scheduler_g.step()
scheduler_d.step()
if rank == 0:
print('Time taken for epoch {} is {} sec\n'.format(epoch + 1, int(time.time() - start)))
def main():
print('Initializing Training Process..')
parser = argparse.ArgumentParser()
# 加载并解析参数
# group_name表示分组名称
parser.add_argument('--group_name', default=None)
# input_wavs_dir表示输入的音频文件夹
parser.add_argument('--input_wavs_dir', default='LJSpeech-1.1/wavs')
# input_mels_dir表示输入的mel谱文件夹
parser.add_argument('--input_mels_dir', default='ft_dataset')
# input_training_file表示输入的训练文件
parser.add_argument('--input_training_file', default='LJSpeech-1.1/training.txt')
# input_validation_file表示输入的验证文件
parser.add_argument('--input_validation_file', default='LJSpeech-1.1/validation.txt')
# checkpoint_path表示检查点路径
parser.add_argument('--checkpoint_path', default='cp_hifigan')
# config表示配置文件
parser.add_argument('--config', default='')
# training_epoches训练的总周期数。默认值为3100。
parser.add_argument('--training_epochs', default=3100, type=int)
# stdout_interval: 标准输出日志的间隔步数。默认值为5。
parser.add_argument('--stdout_interval', default=5, type=int)
# checkpoint_interval: 检查点保存的间隔步数。默认值为5000。
parser.add_argument('--checkpoint_interval', default=5000, type=int)
# summary_interval: TensorBoard摘要记录的间隔步数。默认值为100。
parser.add_argument('--summary_interval', default=100, type=int)
# validation_interval: 验证的间隔步数。默认值为1000。
parser.add_argument('--validation_interval', default=1000, type=int)
# fine_tuning: 是否进行微调。默认值为False。
parser.add_argument('--fine_tuning', default=False, type=bool)
a = parser.parse_args()
# 读取配置文件
with open(a.config) as f:
data = f.read()
# 解析json文件
json_config = json.loads(data)
# 将json文件转换为字典
h = AttrDict(json_config)
# 根据配置文件创建对应文件
build_env(a.config, 'config.json', a.checkpoint_path)
# 设置随机种子,确保训练的可重复性
torch.manual_seed(h.seed)
# 检测GPU,如果多个GPU就同时训练
if torch.cuda.is_available():
torch.cuda.manual_seed(h.seed)
h.num_gpus = torch.cuda.device_count()
h.batch_size = int(h.batch_size / h.num_gpus)
print('Batch size per GPU :', h.batch_size)
else:
pass
if h.num_gpus > 1:
# 多个GPU的训练方式
mp.spawn(train, nprocs=h.num_gpus, args=(a, h,))
else:
# 一个GPU的训练方式
train(0, a, h)
if __name__ == '__main__':
main()