train.py 4.6 KB
Newer Older
G
guosheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
G
guosheng 已提交
19
import random
G
guosheng 已提交
20 21 22 23 24 25
from functools import partial

import numpy as np
import paddle.fluid as fluid
from paddle.fluid.io import DataLoader

G
guosheng 已提交
26
from model import Input, set_device
G
guosheng 已提交
27
from metrics import Metric
G
guosheng 已提交
28
from callbacks import ProgBarLogger
G
guosheng 已提交
29 30 31
from args import parse_args
from seq2seq_base import BaseModel, CrossEntropyCriterion
from seq2seq_attn import AttentionModel
G
guosheng 已提交
32
from reader import create_data_loader
G
guosheng 已提交
33 34


G
guosheng 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
class TrainCallback(ProgBarLogger):
    def __init__(self, args, ppl, verbose=2):
        super(TrainCallback, self).__init__(1, verbose)
        # control metric
        self.ppl = ppl
        self.batch_size = args.batch_size

    def on_train_begin(self, logs=None):
        super(TrainCallback, self).on_train_begin(logs)
        self.train_metrics += ["ppl"]  # remove loss to not print it
        self.ppl.reset()

    def on_train_batch_end(self, step, logs=None):
        batch_loss = logs["loss"][0]
        self.ppl.total_loss += batch_loss * self.batch_size
        logs["ppl"] = np.exp(self.ppl.total_loss / self.ppl.word_count)
        if step > 0 and step % self.ppl.reset_freq == 0:
            self.ppl.reset()
        super(TrainCallback, self).on_train_batch_end(step, logs)

    def on_eval_begin(self, logs=None):
        super(TrainCallback, self).on_eval_begin(logs)
        self.eval_metrics = ["ppl"]
        self.ppl.reset()

    def on_eval_batch_end(self, step, logs=None):
        batch_loss = logs["loss"][0]
        self.ppl.total_loss += batch_loss * self.batch_size
        logs["ppl"] = np.exp(self.ppl.total_loss / self.ppl.word_count)
        super(TrainCallback, self).on_eval_batch_end(step, logs)


class PPL(Metric):
    def __init__(self, reset_freq=100, name=None):
        super(PPL, self).__init__()
        self._name = name or "ppl"
        self.reset_freq = reset_freq
        self.reset()

    def add_metric_op(self, pred, label):
        seq_length = label[0]
        word_num = fluid.layers.reduce_sum(seq_length)
        return word_num

    def update(self, word_num):
        self.word_count += word_num
        return word_num

    def reset(self):
        self.total_loss = 0
        self.word_count = 0

    def accumulate(self):
        return self.word_count

    def name(self):
        return self._name


G
guosheng 已提交
94 95
def do_train(args):
    device = set_device("gpu" if args.use_gpu else "cpu")
G
guosheng 已提交
96 97 98 99 100
    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 已提交
101 102 103 104 105 106 107 108 109

    # 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 已提交
110 111
    ]
    labels = [
G
guosheng 已提交
112 113
        Input(
            [None], "int64", name="trg_length"),
G
guosheng 已提交
114 115
        Input(
            [None, None, 1], "int64", name="label"),
G
guosheng 已提交
116 117
    ]

G
guosheng 已提交
118
    # def dataloader
G
guosheng 已提交
119
    train_loader, eval_loader = create_data_loader(args, device)
G
guosheng 已提交
120

G
guosheng 已提交
121 122 123 124
    model_maker = AttentionModel if args.attention else BaseModel
    model = model_maker(args.src_vocab_size, args.tar_vocab_size,
                        args.hidden_size, args.hidden_size, args.num_layers,
                        args.dropout)
G
guosheng 已提交
125 126 127 128
    optimizer = fluid.optimizer.Adam(
        learning_rate=args.learning_rate, parameter_list=model.parameters())
    optimizer._grad_clip = fluid.clip.GradientClipByGlobalNorm(
        clip_norm=args.max_grad_norm)
G
guosheng 已提交
129
    ppl_metric = PPL()
G
guosheng 已提交
130
    model.prepare(
G
guosheng 已提交
131 132 133 134 135
        optimizer,
        CrossEntropyCriterion(),
        ppl_metric,
        inputs=inputs,
        labels=labels)
G
guosheng 已提交
136
    model.fit(train_data=train_loader,
G
guosheng 已提交
137
              eval_data=eval_loader,
G
guosheng 已提交
138
              epochs=args.max_epoch,
G
guosheng 已提交
139 140
              eval_freq=1,
              save_freq=1,
G
guosheng 已提交
141
              save_dir=args.model_path,
G
guosheng 已提交
142
              callbacks=[TrainCallback(args, ppl_metric)])
G
guosheng 已提交
143 144 145 146 147


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