utils.py 7.7 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.

15 16 17 18
import itertools
import os
import time

19 20
import argparse
import ruamel.yaml
21 22 23 24
import numpy as np
import paddle.fluid.dygraph as dg


25 26 27 28
def str2bool(v):
    return v.lower() in ("true", "t", "1")


29
def add_config_options_to_parser(parser):
30 31 32 33 34
    parser.add_argument(
        '--valid_size', type=int, help="size of the valid dataset")
    parser.add_argument(
        '--segment_length',
        type=int,
35
        help="the length of audio clip for training")
36 37 38 39 40
    parser.add_argument(
        '--sample_rate', type=int, help="sampling rate of audio data file")
    parser.add_argument(
        '--fft_window_shift',
        type=int,
41
        help="the shift of fft window for each frame")
42 43 44
    parser.add_argument(
        '--fft_window_size',
        type=int,
45
        help="the size of fft window for each frame")
46 47 48 49 50
    parser.add_argument(
        '--fft_size', type=int, help="the size of fft filter on each frame")
    parser.add_argument(
        '--mel_bands',
        type=int,
51
        help="the number of mel bands when calculating mel spectrograms")
52 53 54
    parser.add_argument(
        '--mel_fmin',
        type=float,
55
        help="lowest frequency in calculating mel spectrograms")
56 57 58
    parser.add_argument(
        '--mel_fmax',
        type=float,
59 60
        help="highest frequency in calculating mel spectrograms")

61 62
    parser.add_argument(
        '--seed', type=int, help="seed of random initialization for the model")
63
    parser.add_argument('--learning_rate', type=float)
64 65 66 67 68 69 70
    parser.add_argument(
        '--batch_size', type=int, help="batch size for training")
    parser.add_argument(
        '--test_every', type=int, help="test interval during training")
    parser.add_argument(
        '--save_every',
        type=int,
71
        help="checkpointing interval during training")
72 73
    parser.add_argument(
        '--max_iterations', type=int, help="maximum training iterations")
74

75 76 77
    parser.add_argument(
        '--sigma',
        type=float,
78
        help="standard deviation of the latent Gaussian variable")
79 80 81 82
    parser.add_argument('--n_flows', type=int, help="number of flows")
    parser.add_argument(
        '--n_group',
        type=int,
83
        help="number of adjacent audio samples to squeeze into one column")
84 85 86
    parser.add_argument(
        '--n_layers',
        type=int,
87
        help="number of conv2d layer in one wavenet-like flow architecture")
88 89 90 91 92
    parser.add_argument(
        '--n_channels', type=int, help="number of residual channels in flow")
    parser.add_argument(
        '--kernel_h',
        type=int,
93
        help="height of the kernel in the conv2d layer")
94 95 96 97 98
    parser.add_argument(
        '--kernel_w', type=int, help="width of the kernel in the conv2d layer")

    parser.add_argument('--config', type=str, help="Path to the config file.")

99

100 101 102 103 104 105 106 107 108
def add_yaml_config(config):
    with open(config.config, 'rt') as f:
        yaml_cfg = ruamel.yaml.safe_load(f)
    cfg_vars = vars(config)
    for k, v in yaml_cfg.items():
        if k in cfg_vars and cfg_vars[k] is not None:
            continue
        cfg_vars[k] = v
    return config
109 110 111


def load_latest_checkpoint(checkpoint_dir, rank=0):
K
Kexin Zhao 已提交
112 113 114 115 116 117 118 119 120 121
    """Get the iteration number corresponding to the latest saved checkpoint

    Args:
        checkpoint_dir (str): the directory where checkpoint is saved.
        rank (int, optional): the rank of the process in multi-process setting.
            Defaults to 0.

    Returns:
        int: the latest iteration number.
    """
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    checkpoint_path = os.path.join(checkpoint_dir, "checkpoint")
    # Create checkpoint index file if not exist.
    if (not os.path.isfile(checkpoint_path)) and rank == 0:
        with open(checkpoint_path, "w") as handle:
            handle.write("model_checkpoint_path: step-0")

    # Make sure that other process waits until checkpoint file is created
    # by process 0.
    while not os.path.isfile(checkpoint_path):
        time.sleep(1)

    # Fetch the latest checkpoint index.
    with open(checkpoint_path, "r") as handle:
        latest_checkpoint = handle.readline().split()[-1]
        iteration = int(latest_checkpoint.split("-")[-1])

    return iteration


def save_latest_checkpoint(checkpoint_dir, iteration):
K
Kexin Zhao 已提交
142 143 144 145 146 147 148 149 150
    """Save the iteration number of the latest model to be checkpointed.

    Args:
        checkpoint_dir (str): the directory where checkpoint is saved.
        iteration (int): the latest iteration number.

    Returns:
        None
    """
151 152 153 154 155 156
    checkpoint_path = os.path.join(checkpoint_dir, "checkpoint")
    # Update the latest checkpoint index.
    with open(checkpoint_path, "w") as handle:
        handle.write("model_checkpoint_path: step-{}".format(iteration))


157 158 159 160 161
def load_parameters(checkpoint_dir,
                    rank,
                    model,
                    optimizer=None,
                    iteration=None,
162 163
                    file_path=None,
                    dtype="float32"):
K
Kexin Zhao 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    """Load a specific model checkpoint from disk.

    Args:
        checkpoint_dir (str): the directory where checkpoint is saved.
        rank (int): the rank of the process in multi-process setting.
        model (obj): model to load parameters.
        optimizer (obj, optional): optimizer to load states if needed.
            Defaults to None.
        iteration (int, optional): if specified, load the specific checkpoint,
            if not specified, load the latest one. Defaults to None.
        file_path (str, optional): if specified, load the checkpoint
            stored in the file_path. Defaults to None.
        dtype (str, optional): precision of the model parameters.
            Defaults to float32.

    Returns:
        None
    """
182 183 184 185 186 187 188 189
    if file_path is None:
        if iteration is None:
            iteration = load_latest_checkpoint(checkpoint_dir, rank)
        if iteration == 0:
            return
        file_path = "{}/step-{}".format(checkpoint_dir, iteration)

    model_dict, optimizer_dict = dg.load_dygraph(file_path)
190 191 192 193 194 195
    if dtype == "float16":
        for k, v in model_dict.items():
            if "conv2d_transpose" in k:
                model_dict[k] = v.astype("float32")
            else:
                model_dict[k] = v.astype(dtype)
196 197 198 199 200
    model.set_dict(model_dict)
    print("[checkpoint] Rank {}: loaded model from {}".format(rank, file_path))
    if optimizer and optimizer_dict:
        optimizer.set_dict(optimizer_dict)
        print("[checkpoint] Rank {}: loaded optimizer state from {}".format(
201
            rank, file_path))
202 203 204


def save_latest_parameters(checkpoint_dir, iteration, model, optimizer=None):
K
Kexin Zhao 已提交
205 206 207 208 209 210 211 212 213 214 215 216
    """Checkpoint the latest trained model parameters.

    Args:
        checkpoint_dir (str): the directory where checkpoint is saved.
        iteration (int): the latest iteration number.
        model (obj): model to be checkpointed.
        optimizer (obj, optional): optimizer to be checkpointed.
            Defaults to None.

    Returns:
        None
    """
217 218 219 220 221 222 223 224 225
    file_path = "{}/step-{}".format(checkpoint_dir, iteration)
    model_dict = model.state_dict()
    dg.save_dygraph(model_dict, file_path)
    print("[checkpoint] Saved model to {}".format(file_path))

    if optimizer:
        opt_dict = optimizer.state_dict()
        dg.save_dygraph(opt_dict, file_path)
        print("[checkpoint] Saved optimzier state to {}".format(file_path))