wavenet.py 7.1 KB
Newer Older
L
lifuchen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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.

K
Kexin Zhao 已提交
15 16 17 18 19 20 21
import itertools
import os
import time

import librosa
import numpy as np
import paddle.fluid.dygraph as dg
K
Kexin Zhao 已提交
22
from paddle import fluid
K
Kexin Zhao 已提交
23 24 25

import utils
from data import LJSpeech
K
Kexin Zhao 已提交
26
from wavenet_modules import WaveNetModule
K
Kexin Zhao 已提交
27 28 29


class WaveNet():
L
lifuchen 已提交
30 31 32 33 34 35 36
    def __init__(self,
                 config,
                 checkpoint_dir,
                 parallel=False,
                 rank=0,
                 nranks=1,
                 tb_logger=None):
K
Kexin Zhao 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50
        # Process config to calculate the context size
        dilations = list(
            itertools.islice(
                itertools.cycle(config.dilation_block), config.layers))
        config.context_size = sum(dilations) + 1
        self.config = config
        self.checkpoint_dir = checkpoint_dir
        self.parallel = parallel
        self.rank = rank
        self.nranks = nranks
        self.tb_logger = tb_logger

    def build(self, training=True):
        config = self.config
L
lifuchen 已提交
51
        dataset = LJSpeech(config, self.nranks, self.rank)
K
Kexin Zhao 已提交
52 53 54 55
        self.trainloader = dataset.trainloader
        self.validloader = dataset.validloader

        wavenet = WaveNetModule("wavenet", config, self.rank)
L
lifuchen 已提交
56

K
Kexin Zhao 已提交
57 58 59 60 61 62 63 64 65 66
        # Dry run once to create and initalize all necessary parameters.
        audio = dg.to_variable(np.random.randn(1, 20000).astype(np.float32))
        mel = dg.to_variable(
            np.random.randn(1, 100, self.config.mel_bands).astype(np.float32))
        audio_start = dg.to_variable(np.array([0], dtype=np.int32))
        wavenet(audio, mel, audio_start)

        if training:
            # Create Learning rate scheduler.
            lr_scheduler = dg.ExponentialDecay(
L
lifuchen 已提交
67 68 69
                learning_rate=config.learning_rate,
                decay_steps=config.anneal.every,
                decay_rate=config.anneal.rate,
K
Kexin Zhao 已提交
70
                staircase=True)
L
lifuchen 已提交
71

K
Kexin Zhao 已提交
72 73
            optimizer = fluid.optimizer.AdamOptimizer(
                learning_rate=lr_scheduler)
L
lifuchen 已提交
74

K
Kexin Zhao 已提交
75 76 77 78
            clipper = fluid.dygraph_grad_clip.GradClipByGlobalNorm(
                config.gradient_max_norm)

            # Load parameters.
L
lifuchen 已提交
79 80 81 82 83 84 85
            utils.load_parameters(
                self.checkpoint_dir,
                self.rank,
                wavenet,
                optimizer,
                iteration=config.iteration,
                file_path=config.checkpoint)
K
Kexin Zhao 已提交
86
            print("Rank {}: checkpoint loaded.".format(self.rank))
L
lifuchen 已提交
87

K
Kexin Zhao 已提交
88 89 90 91
            # Data parallelism.
            if self.parallel:
                strategy = dg.parallel.prepare_context()
                wavenet = dg.parallel.DataParallel(wavenet, strategy)
L
lifuchen 已提交
92

K
Kexin Zhao 已提交
93 94 95 96 97 98
            self.wavenet = wavenet
            self.optimizer = optimizer
            self.clipper = clipper

        else:
            # Load parameters.
L
lifuchen 已提交
99 100 101 102 103 104
            utils.load_parameters(
                self.checkpoint_dir,
                self.rank,
                wavenet,
                iteration=config.iteration,
                file_path=config.checkpoint)
K
Kexin Zhao 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            print("Rank {}: checkpoint loaded.".format(self.rank))

            self.wavenet = wavenet

    def train_step(self, iteration):
        self.wavenet.train()

        start_time = time.time()
        audios, mels, audio_starts = next(self.trainloader)
        load_time = time.time()

        loss, _ = self.wavenet(audios, mels, audio_starts)

        if self.parallel:
            # loss = loss / num_trainers
            loss = self.wavenet.scale_loss(loss)
            loss.backward()
            self.wavenet.apply_collective_grads()
        else:
            loss.backward()

        if isinstance(self.optimizer._learning_rate,
                      fluid.optimizer.LearningRateDecay):
            current_lr = self.optimizer._learning_rate.step().numpy()
        else:
            current_lr = self.optimizer._learning_rate

L
lifuchen 已提交
132 133 134
        self.optimizer.minimize(
            loss,
            grad_clip=self.clipper,
K
Kexin Zhao 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            parameter_list=self.wavenet.parameters())
        self.wavenet.clear_gradients()

        graph_time = time.time()

        if self.rank == 0:
            loss_val = float(loss.numpy()) * self.nranks
            log = "Rank: {} Step: {:^8d} Loss: {:<8.3f} " \
                  "Time: {:.3f}/{:.3f}".format(
                  self.rank, iteration, loss_val,
                  load_time - start_time, graph_time - load_time)
            print(log)

            tb = self.tb_logger
            tb.add_scalar("Train-Loss-Rank-0", loss_val, iteration)
            tb.add_scalar("Learning-Rate", current_lr, iteration)

    @dg.no_grad
    def valid_step(self, iteration):
        self.wavenet.eval()

        total_loss = []
        sample_audios = []
K
Kexin Zhao 已提交
158
        start_time = time.time()
K
Kexin Zhao 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172
        for audios, mels, audio_starts in self.validloader():
            loss, sample_audio = self.wavenet(audios, mels, audio_starts, True)
            total_loss.append(float(loss.numpy()))
            sample_audios.append(sample_audio)
        total_time = time.time() - start_time

        if self.rank == 0:
            loss_val = np.mean(total_loss)
            log = "Test | Rank: {} AvgLoss: {:<8.3f} Time {:<8.3f}".format(
                self.rank, loss_val, total_time)
            print(log)

            tb = self.tb_logger
            tb.add_scalar("Valid-Avg-Loss", loss_val, iteration)
L
lifuchen 已提交
173 174 175 176 177 178 179 180 181 182
            tb.add_audio(
                "Teacher-Forced-Audio-0",
                sample_audios[0].numpy(),
                iteration,
                sample_rate=self.config.sample_rate)
            tb.add_audio(
                "Teacher-Forced-Audio-1",
                sample_audios[1].numpy(),
                iteration,
                sample_rate=self.config.sample_rate)
K
Kexin Zhao 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

    @dg.no_grad
    def infer(self, iteration):
        self.wavenet.eval()

        config = self.config
        sample = config.sample

        output = "{}/{}/iter-{}".format(config.output, config.name, iteration)
        os.makedirs(output, exist_ok=True)

        filename = "{}/valid_{}.wav".format(output, sample)
        print("Synthesize sample {}, save as {}".format(sample, filename))

        mels_list = [mels for _, mels, _ in self.validloader()]
        start_time = time.time()
        syn_audio = self.wavenet.synthesize(mels_list[sample])
        syn_time = time.time() - start_time
L
lifuchen 已提交
201 202 203
        print("audio shape {}, synthesis time {}".format(syn_audio.shape,
                                                         syn_time))
        librosa.output.write_wav(filename, syn_audio, sr=config.sample_rate)
K
Kexin Zhao 已提交
204 205 206 207 208

    def save(self, iteration):
        utils.save_latest_parameters(self.checkpoint_dir, iteration,
                                     self.wavenet, self.optimizer)
        utils.save_latest_checkpoint(self.checkpoint_dir, iteration)