train.py 4.11 KB
Newer Older
1
2
import logging
import pathlib
3
from argparse import ArgumentParser
4

5
from common import MODEL_TYPE_LIBRISPEECH, MODEL_TYPE_TEDLIUM3, MODEL_TYPE_MUSTC
6
from librispeech.lightning import LibriSpeechRNNTModule
7
from mustc.lightning import MuSTCRNNTModule
8
9
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
10
from tedlium3.lightning import TEDLIUM3RNNTModule
11
12


13
def get_trainer(args):
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    checkpoint_dir = args.exp_dir / "checkpoints"
    checkpoint = ModelCheckpoint(
        checkpoint_dir,
        monitor="Losses/val_loss",
        mode="min",
        save_top_k=5,
        save_weights_only=True,
        verbose=True,
    )
    train_checkpoint = ModelCheckpoint(
        checkpoint_dir,
        monitor="Losses/train_loss",
        mode="min",
        save_top_k=5,
        save_weights_only=True,
        verbose=True,
    )
    callbacks = [
        checkpoint,
        train_checkpoint,
    ]
35
    return Trainer(
36
37
38
39
40
41
        default_root_dir=args.exp_dir,
        max_epochs=args.epochs,
        num_nodes=args.num_nodes,
        gpus=args.gpus,
        accelerator="gpu",
        strategy="ddp",
42
        gradient_clip_val=args.gradient_clip_val,
43
44
45
46
        callbacks=callbacks,
    )


47
48
49
50
51
52
53
54
55
56
57
58
59
def get_lightning_module(args):
    if args.model_type == MODEL_TYPE_LIBRISPEECH:
        return LibriSpeechRNNTModule(
            librispeech_path=str(args.dataset_path),
            sp_model_path=str(args.sp_model_path),
            global_stats_path=str(args.global_stats_path),
        )
    elif args.model_type == MODEL_TYPE_TEDLIUM3:
        return TEDLIUM3RNNTModule(
            tedlium_path=str(args.dataset_path),
            sp_model_path=str(args.sp_model_path),
            global_stats_path=str(args.global_stats_path),
        )
60
61
62
63
64
65
    elif args.model_type == MODEL_TYPE_MUSTC:
        return MuSTCRNNTModule(
            mustc_path=str(args.dataset_path),
            sp_model_path=str(args.sp_model_path),
            global_stats_path=str(args.global_stats_path),
        )
66
67
    else:
        raise ValueError(f"Encountered unsupported model type {args.model_type}.")
68

69
70
71

def parse_args():
    parser = ArgumentParser()
72
    parser.add_argument(
73
74
75
76
        "--model-type", type=str, choices=[MODEL_TYPE_LIBRISPEECH, MODEL_TYPE_TEDLIUM3, MODEL_TYPE_MUSTC], required=True
    )
    parser.add_argument(
        "--global-stats-path",
77
78
79
        default=pathlib.Path("global_stats.json"),
        type=pathlib.Path,
        help="Path to JSON file containing feature means and stddevs.",
80
        required=True,
81
82
    )
    parser.add_argument(
83
        "--dataset-path",
84
        type=pathlib.Path,
85
        help="Path to datasets.",
86
87
88
        required=True,
    )
    parser.add_argument(
89
        "--sp-model-path",
90
91
92
        type=pathlib.Path,
        help="Path to SentencePiece model.",
        required=True,
93
94
    )
    parser.add_argument(
95
        "--exp-dir",
96
        default=pathlib.Path("./exp"),
97
        type=pathlib.Path,
98
        help="Directory to save checkpoints and logs to. (Default: './exp')",
99
100
    )
    parser.add_argument(
101
        "--num-nodes",
102
        default=4,
103
        type=int,
104
        help="Number of nodes to use for training. (Default: 4)",
105
106
107
108
109
110
111
112
113
114
115
116
117
    )
    parser.add_argument(
        "--gpus",
        default=8,
        type=int,
        help="Number of GPUs per node to use for training. (Default: 8)",
    )
    parser.add_argument(
        "--epochs",
        default=120,
        type=int,
        help="Number of epochs to train for. (Default: 120)",
    )
118
    parser.add_argument(
119
        "--gradient-clip-val", default=10.0, type=float, help="Value to clip gradient values to. (Default: 10.0)"
120
    )
121
122
123
124
    parser.add_argument("--debug", action="store_true", help="whether to use debug level for logging")
    return parser.parse_args()


125
def init_logger(debug):
126
127
128
129
130
131
    fmt = "%(asctime)s %(message)s" if debug else "%(message)s"
    level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(format=fmt, level=level, datefmt="%Y-%m-%d %H:%M:%S")


def cli_main():
132
133
134
135
136
    args = parse_args()
    init_logger(args.debug)
    model = get_lightning_module(args)
    trainer = get_trainer(args)
    trainer.fit(model)
137
138
139
140


if __name__ == "__main__":
    cli_main()