def evaluate(hps, generator, eval_loader, writer_eval): generator.eval() with torch.no_grad(): for batch_idx, (spec, spec_lengths, y, y_lengths) in enumerate(eval_loader): spec, spec_lengths = spec.cuda(0), spec_lengths.cuda(0) y, y_lengths = y.cuda(0), y_lengths.cuda(0) # remove else spec = spec[:1] spec_lengths = spec_lengths[:1] y = y[:1] y_lengths = y_lengths[:1] break mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_hat, mask, *_ = generator.module.infer(mel, spec_lengths, max_len=1000) y_hat_lengths = mask.sum([1,2]).long() * hps.data.hop_length mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1).float(), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) image_dict = { "gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()) } audio_dict = { "gen/audio": y_hat[0,:,:y_hat_lengths[0]] } if global_step == 0: image_dict.update({"gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())}) audio_dict.update({"gt/audio": y[0,:,:y_lengths[0]]}) utils.summarize( writer=writer_eval, global_step=global_step, images=image_dict, audios=audio_dict, audio_sampling_rate=hps.data.sampling_rate ) generator.train()
def train(rank, epoch, hps, generator, optimizer_g, train_loader, logger, writer): train_loader.sampler.set_epoch(epoch) global global_step generator.train() for batch_idx, (x, x_lengths, y, y_lengths) in enumerate(train_loader): x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) # Train Generator optimizer_g.zero_grad() (z, y_m, y_logs, logdet), attn, logw, logw_, x_m, x_logs = generator(x, x_lengths, y, y_lengths, gen=False) l_mle = 0.5 * math.log(2 * math.pi) + (torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m)**2) - torch.sum(logdet)) / (torch.sum(y_lengths // hps.model.n_sqz) * hps.model.n_sqz * hps.data.n_mel_channels) l_length = torch.sum((logw - logw_)**2) / torch.sum(x_lengths) loss_gs = [l_mle, l_length] loss_g = sum(loss_gs) if hps.train.fp16_run: with amp.scale_loss(loss_g, optimizer_g._optim) as scaled_loss: scaled_loss.backward() grad_norm = commons.clip_grad_value_(amp.master_params(optimizer_g._optim), 5) else: loss_g.backward() grad_norm = commons.clip_grad_value_(generator.parameters(), 5) optimizer_g.step() if rank==0: if batch_idx % hps.train.log_interval == 0: (y_gen, *_), *_ = generator.module(x[:1], x_lengths[:1], gen=True) logger.info('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(x), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss_g.item())) logger.info([x.item() for x in loss_gs] + [global_step, optimizer_g.get_lr()]) scalar_dict = {"loss/g/total": loss_g, "learning_rate": optimizer_g.get_lr(), "grad_norm": grad_norm} scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(loss_gs)}) utils.summarize( writer=writer, global_step=global_step, images={"y_org": utils.plot_spectrogram_to_numpy(y[0].data.cpu().numpy()), "y_gen": utils.plot_spectrogram_to_numpy(y_gen[0].data.cpu().numpy()), "attn": utils.plot_alignment_to_numpy(attn[0,0].data.cpu().numpy()), }, scalars=scalar_dict) global_step += 1 if rank == 0: logger.info('====> Epoch: {}'.format(epoch))
def add_spec_sample(writer, mel_target, mel_predicted, steps): writer.add_image("mel_target", plot_spectrogram_to_numpy(mel_target), steps) writer.add_image("mel_predicted", plot_spectrogram_to_numpy(mel_predicted), steps)
def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): net_g, net_d = nets optim_g, optim_d = optims scheduler_g, scheduler_d = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() for batch_idx, (spec, spec_lengths, y, y_lengths) in enumerate(train_loader): spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) # print('check',mel.shape)/ y_hat, ids_slice, x_mask, z_mask,\ (z, z_p, m_p, logs_p, m_q, logs_q) = net_g(mel, spec_lengths, spec, spec_lengths) # print('check',log_det_j_sum.shape, m_p.shape) y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice # NDA is effective? batch_size=y.size(0) y_jig1 = y.view(batch_size,4,-1) rand_idx = torch.randperm(4) y_jig2 = y_jig1[:,rand_idx,:] y_jigsaw = y_jig2.view(batch_size,1,-1) # print(rand_idx) check_idx = torch.tensor([0,1,2,3]) if (rand_idx ==check_idx).sum()==4: y_jigsaw = y_hat else: y_jigsaw = y_jigsaw y_negative = 0.75*y_hat + 0.25*y_jigsaw # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_negative.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) with autocast(enabled=False): loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl loss_fm = feature_loss(fmap_r, fmap_g) loss_gen, losses_gen = generator_loss(y_d_hat_g) loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl optim_g.zero_grad() scaler.scale(loss_gen_all).backward() scaler.unscale_(optim_g) grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) scaler.step(optim_g) scaler.update() if rank==0: if global_step % hps.train.log_interval == 0: lr = optim_g.param_groups[0]['lr'] losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl] logger.info('Train Epoch: {} [{:.0f}%]'.format( epoch, 100. * batch_idx / len(train_loader))) logger.info([x.item() for x in losses] + [global_step, lr]) scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g} scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/kl": loss_kl}) scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}) image_dict = { "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), } utils.summarize( writer=writer, global_step=global_step, images=image_dict, scalars=scalar_dict) if global_step % hps.train.eval_interval == 0: evaluate(hps, net_g, eval_loader, writer_eval) utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "G_{}.pth".format(global_step))) utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "D_{}.pth".format(global_step))) global_step += 1 if rank == 0: logger.info('====> Epoch: {}'.format(epoch))