train.py 2.8 KB
Newer Older
G
guosheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

import logging
import os
G
guosheng 已提交
17
import random
18
from args import parse_args
G
guosheng 已提交
19 20 21
from functools import partial

import numpy as np
22
import paddle
G
guosheng 已提交
23 24
import paddle.fluid as fluid
from paddle.fluid.io import DataLoader
25
from paddle.static import InputSpec as Input
G
guosheng 已提交
26 27 28

from seq2seq_base import BaseModel, CrossEntropyCriterion
from seq2seq_attn import AttentionModel
G
guosheng 已提交
29
from reader import create_data_loader
30
from utility import PPL, TrainCallback, get_model_cls
G
guosheng 已提交
31 32


G
guosheng 已提交
33
def do_train(args):
34
    device = paddle.set_device("gpu" if args.use_gpu else "cpu")
G
guosheng 已提交
35 36 37 38 39
    fluid.enable_dygraph(device) if args.eager_run else None

    if args.enable_ce:
        fluid.default_main_program().random_seed = 102
        fluid.default_startup_program().random_seed = 102
G
guosheng 已提交
40 41 42 43 44 45 46 47 48

    # define model
    inputs = [
        Input(
            [None, None], "int64", name="src_word"),
        Input(
            [None], "int64", name="src_length"),
        Input(
            [None, None], "int64", name="trg_word"),
G
guosheng 已提交
49 50
    ]
    labels = [
G
guosheng 已提交
51 52
        Input(
            [None], "int64", name="trg_length"),
G
guosheng 已提交
53 54
        Input(
            [None, None, 1], "int64", name="label"),
G
guosheng 已提交
55 56
    ]

G
guosheng 已提交
57
    # def dataloader
G
guosheng 已提交
58
    train_loader, eval_loader = create_data_loader(args, device)
G
guosheng 已提交
59

60 61
    model_maker = get_model_cls(
        AttentionModel) if args.attention else get_model_cls(BaseModel)
62 63 64 65 66
    model = paddle.Model(
        model_maker(args.src_vocab_size, args.tar_vocab_size, args.hidden_size,
                    args.hidden_size, args.num_layers, args.dropout),
        inputs=inputs,
        labels=labels)
G
guosheng 已提交
67
    grad_clip = fluid.clip.GradientClipByGlobalNorm(
G
guosheng 已提交
68
        clip_norm=args.max_grad_norm)
G
guosheng 已提交
69 70 71 72 73
    optimizer = fluid.optimizer.Adam(
        learning_rate=args.learning_rate,
        parameter_list=model.parameters(),
        grad_clip=grad_clip)

74
    ppl_metric = PPL(reset_freq=100)  # ppl for every 100 batches
75
    model.prepare(optimizer, CrossEntropyCriterion(), ppl_metric)
G
guosheng 已提交
76
    model.fit(train_data=train_loader,
G
guosheng 已提交
77
              eval_data=eval_loader,
G
guosheng 已提交
78
              epochs=args.max_epoch,
G
guosheng 已提交
79 80
              eval_freq=1,
              save_freq=1,
G
guosheng 已提交
81
              save_dir=args.model_path,
G
guosheng 已提交
82
              callbacks=[TrainCallback(ppl_metric, args.log_freq)])
G
guosheng 已提交
83 84 85 86 87


if __name__ == "__main__":
    args = parse_args()
    do_train(args)