def validation(generator, validation_loader, sw, h, steps, device, first=False): 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.VOC_sampling_rate, h.hop_size, h.win_size, h.fmin, h.fmax_for_loss) # print(y_mel.shape, y_g_hat_mel.shape) if y_g_hat_mel.size(2) > y_mel.size(2): y_g_hat_mel = y_g_hat_mel[:, :, :y_mel.size(2)] else: y_mel = y_mel[:, :, :y_g_hat_mel.size(2)] val_err_tot += F.l1_loss(y_mel, y_g_hat_mel).item() if j <= 4: if steps == 0 or first: sw.add_audio('gt/y_{}'.format(j), y[0], steps, h.VOC_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.VOC_sampling_rate) y_hat_spec = mel_spectrogram(y_g_hat.squeeze(1), h.n_fft, h.num_mels, h.VOC_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()
def train(rank, a, h): 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) torch.cuda.set_device(rank) 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'] 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)) 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 = batch 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.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 loss_mel = F.l1_loss(y_mel, y_g_hat_mel) * 45 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 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)))
n_columns = int(MAX_MEM_BLOCK / (stft_matrix.shape[0] * stft_matrix.itemsize)) for bl_s in range(0, stft_matrix.shape[1], n_columns): bl_t = min(bl_s + n_columns, stft_matrix.shape[1]) # RFFT and Conjugate here to match phase from DPWE code stft_matrix[:, bl_s:bl_t] = fft.fft( fft_window * y_frames[:, bl_s:bl_t], n=N_FFT, axis=0)[:stft_matrix.shape[0]].conj() windowed = fft_window * y_frames[:, bl_s:bl_t] plt.figure() plt.subplot(1, 2, 1) plt.plot(y_frames[:, 0]) plt.title("Original frame") plt.subplot(1, 2, 2) plt.plot(windowed[:, 0]) plt.title("Windowed frame") # Magnitude of the STFT S = np.abs(stft_matrix) # power spectrum of the STFT S = S ** 2 # log-power spectrum logS = np.log10(S) # show the log-power spectrum plt.figure() plot_spectrogram(logS) plt.show(block=True)
def train(rank, args, hp, hp_str): # if hp.train.num_gpus > 1: # init_process_group(backend=hp.dist.dist_backend, init_method=hp.dist.dist_url, # world_size=hp.dist.world_size * hp.train.num_gpus, rank=rank) torch.cuda.manual_seed(hp.train.seed) device = torch.device('cuda:{:d}'.format(rank)) generator = Generator(hp.model.in_channels, hp.model.out_channels).to(device) specd = SpecDiscriminator().to(device) msd = MultiScaleDiscriminator().to(device) stft_loss = MultiResolutionSTFTLoss() if rank == 0: print(generator) os.makedirs(hp.logs.chkpt_dir, exist_ok=True) print("checkpoints directory : ", hp.logs.chkpt_dir) if os.path.isdir(hp.logs.chkpt_dir): cp_g = scan_checkpoint(hp.logs.chkpt_dir, 'g_') cp_do = scan_checkpoint(hp.logs.chkpt_dir, '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']) specd.load_state_dict(state_dict_do['specd']) msd.load_state_dict(state_dict_do['msd']) steps = state_dict_do['steps'] + 1 last_epoch = state_dict_do['epoch'] if hp.train.num_gpus > 1: generator = DistributedDataParallel(generator, device_ids=[rank]).to(device) specd = DistributedDataParallel(specd, device_ids=[rank]).to(device) msd = DistributedDataParallel(msd, device_ids=[rank]).to(device) optim_g = torch.optim.AdamW( generator.parameters(), hp.train.adamG.lr, betas=[hp.train.adamG.beta1, hp.train.adamG.beta2]) optim_d = torch.optim.AdamW( itertools.chain(msd.parameters(), specd.parameters()), hp.train.adamD.lr, betas=[hp.train.adamD.beta1, hp.train.adamD.beta2]) 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=hp.train.adam.lr_decay, last_epoch=last_epoch) # scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hp.train.adam.lr_decay, last_epoch=last_epoch) training_filelist, validation_filelist = get_dataset_filelist(args) trainset = MelDataset(training_filelist, hp.data.input_wavs, hp.data.output_wavs, hp.audio.segment_length, hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.hop_length, hp.audio.win_length, hp.audio.sampling_rate, hp.audio.mel_fmin, hp.audio.mel_fmax, n_cache_reuse=0, shuffle=False if hp.train.num_gpus > 1 else True, fmax_loss=None, device=device) train_sampler = DistributedSampler( trainset) if hp.train.num_gpus > 1 else None train_loader = DataLoader(trainset, num_workers=hp.train.num_workers, shuffle=False, sampler=train_sampler, batch_size=hp.train.batch_size, pin_memory=True, drop_last=True) if rank == 0: validset = MelDataset(validation_filelist, hp.data.input_wavs, hp.data.output_wavs, hp.audio.segment_length, hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.hop_length, hp.audio.win_length, hp.audio.sampling_rate, hp.audio.mel_fmin, hp.audio.mel_fmax, split=False, shuffle=False, n_cache_reuse=0, fmax_loss=None, device=device) 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(hp.logs.chkpt_dir, 'logs')) generator.train() specd.train() msd.train() with_postnet = False for epoch in range(max(0, last_epoch), args.training_epochs): if rank == 0: start = time.time() print("Epoch: {}".format(epoch + 1)) if hp.train.num_gpus > 1: train_sampler.set_epoch(epoch) for i, batch in enumerate(train_loader): if rank == 0: start_b = time.time() if steps > hp.train.postnet_start_steps: with_postnet = True x, y, file, _, y_mel_loss = batch x = torch.autograd.Variable(x.to(device, non_blocking=True)) y = torch.autograd.Variable(y.to(device, non_blocking=True)) y_mel_loss = torch.autograd.Variable( y_mel_loss.to(device, non_blocking=True)) # y_mel = torch.autograd.Variable(y_mel.to(device, non_blocking=True)) x = x.unsqueeze(1) y = y.unsqueeze(1) before_y_g_hat, y_g_hat = generator(x, with_postnet) if y_g_hat is not None: y_g_hat_mel = mel_spectrogram( y_g_hat.squeeze(1), hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.sampling_rate, hp.audio.hop_length, hp.audio.win_length, hp.audio.mel_fmin, None) if steps > hp.train.discriminator_train_start_steps: for _ in range(hp.train.rep_discriminator): optim_d.zero_grad() # SpecD y_df_hat_r, y_df_hat_g, _, _ = specd( y_mel_loss, y_g_hat_mel.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() before_y_g_hat_mel = mel_spectrogram( before_y_g_hat.squeeze(1), hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.sampling_rate, hp.audio.hop_length, hp.audio.win_length, hp.audio.mel_fmin, None) # Generator optim_g.zero_grad() # L1 Mel-Spectrogram Loss # before_loss_mel = F.l1_loss(y_mel_loss, before_y_g_hat_mel) sc_loss, mag_loss = stft_loss( before_y_g_hat[:, :, :y.size(2)].squeeze(1), y.squeeze(1)) before_loss_mel = sc_loss + mag_loss # L1 Sample Loss before_loss_sample = F.l1_loss(y, before_y_g_hat) loss_gen_all = before_loss_mel + before_loss_sample if y_g_hat is not None: # L1 Mel-Spectrogram Loss # loss_mel = F.l1_loss(y_mel_loss, y_g_hat_mel) sc_loss_, mag_loss_ = stft_loss( y_g_hat[:, :, :y.size(2)].squeeze(1), y.squeeze(1)) loss_mel = sc_loss_ + mag_loss_ # L1 Sample Loss loss_sample = F.l1_loss(y, y_g_hat) loss_gen_all += loss_mel + loss_sample if steps > hp.train.discriminator_train_start_steps: y_df_hat_r, y_df_hat_g, fmap_f_r, fmap_f_g = specd( y_mel_loss, y_g_hat_mel) 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 += hp.model.lambda_adv * ( loss_gen_s + loss_gen_f + loss_fm_s + loss_fm_f) loss_gen_all.backward() optim_g.step() if rank == 0: # STDOUT logging if steps % args.stdout_interval == 0: with torch.no_grad(): mel_error = F.l1_loss(y_mel_loss, before_y_g_hat_mel).item() sample_error = F.l1_loss(y, before_y_g_hat) print( 'Steps : {:d}, Gen Loss Total : {:4.3f}, Sample Error: {:4.3f}, ' 'Mel-Spec. Error : {:4.3f}, s/b : {:4.3f}'.format( steps, loss_gen_all, sample_error, mel_error, time.time() - start_b)) # checkpointing if steps % hp.logs.save_interval == 0 and steps != 0: checkpoint_path = "{}/g_{:08d}".format( hp.logs.chkpt_dir, steps) save_checkpoint( checkpoint_path, { 'generator': (generator.module if hp.train.num_gpus > 1 else generator).state_dict() }) checkpoint_path = "{}/do_{:08d}".format( hp.logs.chkpt_dir, steps) save_checkpoint( checkpoint_path, { 'specd': (specd.module if hp.train.num_gpus > 1 else specd).state_dict(), 'msd': (msd.module if hp.train.num_gpus > 1 else msd).state_dict(), 'optim_g': optim_g.state_dict(), 'optim_d': optim_d.state_dict(), 'steps': steps, 'epoch': epoch, 'hp_str': hp_str }) # Tensorboard summary logging if steps % hp.logs.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 % hp.logs.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, file, y_mel, y_mel_loss = batch x = x.unsqueeze(1) y = y.unsqueeze(1).to(device) before_y_g_hat, y_g_hat = generator(x.to(device)) y_mel_loss = torch.autograd.Variable( y_mel_loss.to(device, non_blocking=True)) y_g_hat_mel = mel_spectrogram( before_y_g_hat.squeeze(1), hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.sampling_rate, hp.audio.hop_length, hp.audio.win_length, hp.audio.mel_fmin, None) val_err_tot += F.l1_loss(y_mel_loss, y_g_hat_mel).item() val_err_tot += F.l1_loss(y, before_y_g_hat).item() if y_g_hat is not None: val_err_tot += F.l1_loss(y, y_g_hat).item() if j <= 4: if steps == 0: sw.add_audio('gt_noise/y_{}'.format(j), x[0], steps, hp.audio.sampling_rate) sw.add_audio('gt_clean/y_{}'.format(j), y[0], steps, hp.audio.sampling_rate) sw.add_figure( 'gt/y_spec_clean_{}'.format(j), plot_spectrogram(y_mel[0]), steps) sw.add_audio('generated/y_hat_{}'.format(j), before_y_g_hat[0], steps, hp.audio.sampling_rate) if y_g_hat is not None: sw.add_audio( 'generated/y_hat_after_{}'.format(j), y_g_hat[0], steps, hp.audio.sampling_rate) y_hat_spec = mel_spectrogram( before_y_g_hat.squeeze(1), hp.audio.filter_length, hp.audio.n_mel_channels, hp.audio.sampling_rate, hp.audio.hop_length, hp.audio.win_length, hp.audio.mel_fmin, None) 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 train(rank, a, h): 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( h["discriminator_periods"] if "discriminator_periods" in h.keys() else None).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 not None: state_dict_g = load_checkpoint(cp_g, device) gsd = generator.state_dict() gsd.update({ k: v for k, v in state_dict_g['generator'].items() if k in gsd and state_dict_g['generator'][k].shape == gsd[k].shape }) missing_keys = { k: v for k, v in state_dict_g['generator'].items() if not (k in gsd and state_dict_g['generator'][k].shape == gsd[k].shape) }.keys() generator.load_state_dict(gsd) del gsd, state_dict_g if cp_do is None or len(missing_keys) or a.from_zero: state_dict_do = None last_epoch = -1 else: state_dict_do = load_checkpoint(cp_do, device) mpd.load_state_dict(state_dict_do['mpd']) del state_dict_do['mpd'] msd.load_state_dict(state_dict_do['msd']) del state_dict_do['msd'] steps = state_dict_do['steps'] + 1 last_epoch = state_dict_do['epoch'] 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']) del state_dict_do 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, h.segment_size, h.sampling_rate) 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, trim_non_voiced=a.trim_non_voiced) STFT = STFT_Class(h.sampling_rate, h.num_mels, h.n_fft, h.win_size, h.hop_size, h.fmin, h.fmax) 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) assert len(train_loader), 'No audio files in dataset!' 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, trim_non_voiced=a.trim_non_voiced) validation_loader = DataLoader(validset, num_workers=h.num_workers, shuffle=False, sampler=None, batch_size=1, pin_memory=True, drop_last=True) sw = SummaryWriter(os.path.join(a.checkpoint_path, 'logs'), max_queue=10000) sw.logged_gt_plots = False if h.num_gpus > 1: import gc gc.collect() torch.cuda.empty_cache() 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)) 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 = batch 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.unsqueeze(1) y_g_hat = generator(x) y_g_hat_mel = STFT.get_mel(y_g_hat.squeeze(1)) 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 loss_mel = F.l1_loss(y_mel, y_g_hat_mel) 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 * 45 loss_gen_all.backward() optim_g.step() if rank == 0: torch.set_grad_enabled(False) # STDOUT logging if steps % a.stdout_interval == 0: print( 'Steps : {:d}, Gen Loss Total : {:4.3f}, Mel-Spec. Error : {:4.3f}, s/b : {:4.3f}' .format(steps, loss_gen_all, loss_mel.item(), 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 }) del_old_checkpoints(a.checkpoint_path, 'g_', a.n_models_to_keep) del_old_checkpoints(a.checkpoint_path, 'do_', a.n_models_to_keep) # Tensorboard summary logging if steps % a.summary_interval == 0: sw.add_scalar("training/gen_loss_total", loss_gen_all, steps) sw.add_scalar("training/mel_spec_error", loss_mel.item(), steps) # Validation if steps % a.validation_interval == 0: # and steps != 0: print("Validating...") n_audios_to_plot = 6 generator.eval() torch.cuda.empty_cache() val_err_tot = 0 for j, batch in tqdm(enumerate(validation_loader), total=len(validation_loader)): x, y, _, y_mel = batch y_g_hat = generator(x.to(device)) y_hat_spec = STFT.get_mel(y_g_hat.squeeze(1)) val_err_tot += F.l1_loss(y_mel, y_hat_spec.to(y_mel)).item() if j < n_audios_to_plot and not sw.logged_gt_plots: sw.add_audio(f'gt/y_{j}', y[0], steps, h.sampling_rate) sw.add_figure(f'spec_{j:02}/gt_spec', plot_spectrogram(y_mel[0]), steps) if j < n_audios_to_plot: sw.add_audio(f'generated/y_hat_{j}', y_g_hat[0], steps, h.sampling_rate) sw.add_figure( f'spec_{j:02}/pred_spec', plot_spectrogram( y_hat_spec.squeeze(0).cpu().numpy()), steps) if j > 64: # I am NOT patient enough to complete an entire validation cycle with over 1536 files. break sw.logged_gt_plots = True val_err = val_err_tot / (j + 1) sw.add_scalar("validation/mel_spec_error", val_err, steps) generator.train() print(f"Done. Val_loss = {val_err}") torch.set_grad_enabled(True) 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 fit(a, epochs): if h.num_gpus > 1: init_distributed(a.rank, h.num_gpus, a.group_name, h.dist_config['dist_backend'], h.dist_config['dist_url']) generator = Generator().to(device) discriminator = MultiScaleDiscriminator().to(device) if h.num_gpus > 1: generator = apply_gradient_allreduce(generator) discriminator = apply_gradient_allreduce(discriminator) g_optim = torch.optim.Adam(generator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) d_optim = torch.optim.Adam(discriminator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) steps = 0 if a.cp_g != "" and a.cp_d != "": generator, g_optim, steps = load_checkpoint(a.cp_g, generator, g_optim) discriminator, d_optim, steps = load_checkpoint(a.cp_d, discriminator, d_optim) steps += 1 with open(a.input_train_metafile, 'r', encoding='utf-8') as fi: training_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav') for x in fi.read().split('\n') if len(x) > 0] with open(a.input_valid_metafile, 'r', encoding='utf-8') as fi: validation_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav') for x in fi.read().split('\n') if len(x) > 0] trainset = MelDataset(training_files, h.segment_size, h.n_fft, h.num_mels, h.hop_size, h.win_size, h.sampling_rate, h.fmin, h.fmax) 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=False, drop_last=True) if a.rank == 0: validset = MelDataset(validation_files, 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) valid_loader = DataLoader(validset, num_workers=1, shuffle=False, sampler=None, batch_size=1, pin_memory=False, drop_last=True) if a.rank == 0: os.makedirs(a.cps, exist_ok=True) print("checkpoints directory : ", a.cps) sw = SummaryWriter(os.path.join(a.cps, 'logs')) epoch_offset = max(0, int(steps / len(train_loader))) generator.train() discriminator.train() for epoch in range(epoch_offset, epochs): start = time.time() if a.rank == 0: print("Epoch: {}".format(epoch)) for i, batch in enumerate(train_loader): start_b = time.time() x, y, _ = batch x = torch.autograd.Variable(x.to(device)) y = torch.autograd.Variable(y.to(device)) y = y.unsqueeze(1) g_optim.zero_grad() y_ghat = generator(x) y_dhat_r, y_dhat_g, fmap_r, fmap_g = discriminator(y, y_ghat) loss_fm = feature_loss(fmap_r, fmap_g) loss_gen = generator_loss(y_dhat_g) + loss_fm if h.num_gpus > 1: reduced_loss_gen = reduce_tensor(loss_gen.data, h.num_gpus).item() else: reduced_loss_gen = loss_gen.item() loss_gen.backward() g_optim.step() d_optim.zero_grad() y_ghat = y_ghat.detach() y_dhat_r, y_dhat_g, _, _ = discriminator(y, y_ghat) loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_dhat_r, y_dhat_g) if h.num_gpus > 1: reduced_loss_disc = reduce_tensor(loss_disc.data, h.num_gpus).item() else: reduced_loss_disc = loss_disc.item() loss_disc.backward() d_optim.step() if a.rank == 0 and steps % a.stdout_interval == 0: print('Steps : {:d}, Gen Loss : {:4.3f}, Disc Loss : {:4.3f}, s/b : {:4.3f}'. format(steps, reduced_loss_gen, reduced_loss_disc, time.time() - start_b)) if a.rank == 0 and steps % a.checkpoint_interval == 0 and steps != 0: checkpoint_path = "{}/g_{:08d}".format(a.cps, steps) save_checkpoint(generator, g_optim, h.learning_rate, steps, checkpoint_path) checkpoint_path = "{}/d_{:08d}".format(a.cps, steps) save_checkpoint(discriminator, d_optim, h.learning_rate, steps, checkpoint_path) if a.rank == 0 and steps % a.summary_interval == 0: sw.add_scalar("training/gen_loss", reduced_loss_gen, steps) sw.add_scalar("training/disc_loss", reduced_loss_disc, steps) for i, (r, g) in enumerate(zip(losses_disc_r, losses_disc_g)): sw.add_scalar("training/disc{:d}_loss_r".format(i+1), r, steps) sw.add_scalar("training/disc{:d}_loss_g".format(i+1), g, steps) for i, (r, g) in enumerate(zip(y_dhat_r, y_dhat_g)): sw.add_histogram("training/disc{:d}_r_output".format(i+1), r, steps) sw.add_histogram("training/disc{:d}_g_output".format(i+1), g, steps) sw.add_histogram("training/gen_output", y_ghat, steps) sw.add_audio('training_gt/y', y[0], steps, h.sampling_rate) sw.add_audio('training_predicted/y_hat', y_ghat[0], steps, h.sampling_rate) if a.rank == 0 and steps % a.validation_interval == 0: # and steps != 0: for i, batch in enumerate(valid_loader): x, y, _ = batch y_ghat = generator(x.to(device)) sw.add_audio('validation_gt/y_{}'.format(i), y[0], steps, h.sampling_rate) sw.add_audio('validation_predicted/y_hat_{}'.format(i), y_ghat[0], steps, h.sampling_rate) # print(plot_spectrogram(x[i])) sw.add_figure('validation_gt/y_spec_{}'.format(i), plot_spectrogram(x[0]), steps) y_hat_spec = mel_spectrogram(y_ghat.detach().cpu().numpy()[0][0], h.n_fft, h.num_mels, h.sampling_rate, h.hop_size, h.win_size, h.fmin, h.fmax, center=False) sw.add_figure('validation_predicted/y_hat_spec_{}'.format(i), plot_spectrogram(y_hat_spec), steps) if i == 4: break steps += 1 if a.rank == 0: print('Time taken for epoch {} is {} sec\n'.format(epoch + 1, int(time.time()-start)))
def train(rank, a, h, resume_run_id=None): 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) cp_g = None cp_do = None if resume_run_id: restored_g = wandb.restore("g_latest") cp_g = restored_g.name restored_do = wandb.restore("do_latest") cp_do = restored_do.name 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"] 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, ) print(f"train dataset size:{len(trainset)}") 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, ) print(f"valid dataset size:{len(validset)}") 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)) 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 = batch 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.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 loss_mel = F.l1_loss(y_mel, y_g_hat_mel) * 45 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)) wandb.log( { "loss/Gen Loss Total": loss_gen_all, "loss/Mel-Spec. Error": mel_error, }, step=steps, ) # checkpointing if steps % a.checkpoint_interval == 0 and steps != 0: # generator 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_name = "g_{:08d}".format(steps) wandb.save(checkpoint_name) # also save as latest checkpoint_path = "{}/g_latest".format(a.checkpoint_path) save_checkpoint( checkpoint_path, { "generator": (generator.module if h.num_gpus > 1 else generator).state_dict() }, ) wandb.save("g_latest") # discriminator 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, }, ) checkpoint_name = "do_{:08d}".format(steps) wandb.save(checkpoint_name) # also save as latest checkpoint_path = "{}/do_latest".format(a.checkpoint_path) 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, }, ) wandb.save("do_latest") # Tensorboard summary logging 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(): samples_orig = [] samples_pred = [] 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, ) # log orig audio to wandb orig_audio = y.squeeze().cpu() samples_orig.append( wandb.Audio( orig_audio, caption=f"sample {i}", sample_rate=h.sampling_rate, )) 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, ) # log pred audio to wandb pred_audio = y_g_hat.squeeze().cpu() samples_pred.append( wandb.Audio( pred_audio, caption=f"sample {i}", sample_rate=h.sampling_rate, )) val_err = val_err_tot / (j + 1) sw.add_scalar("validation/mel_spec_error", val_err, steps) # log audios to wandb wandb.log( { "audio/generated": samples_pred, }, step=steps, ) if steps == 0: wandb.log( { "audio/original": samples_orig, }, step=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)))