predict.py 4.7 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) 2019 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 six
import sys
G
guosheng 已提交
19
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
G
guosheng 已提交
20
from functools import partial
G
guosheng 已提交
21 22 23 24

import numpy as np
import paddle
import paddle.fluid as fluid
G
guosheng 已提交
25 26
from paddle.fluid.io import DataLoader
from paddle.fluid.layers.utils import flatten
G
guosheng 已提交
27 28 29 30

from utils.configure import PDConfig
from utils.check import check_gpu, check_version

G
guosheng 已提交
31 32
from model import Input, set_device
from reader import prepare_infer_input, Seq2SeqDataset, Seq2SeqBatchSampler
G
guosheng 已提交
33
from transformer import InferTransformer, position_encoding_init
G
guosheng 已提交
34 35


G
guosheng 已提交
36 37
def post_process_seq(seq, bos_idx, eos_idx, output_bos=False,
                     output_eos=False):
G
guosheng 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    """
    Post-process the decoded sequence.
    """
    eos_pos = len(seq) - 1
    for i, idx in enumerate(seq):
        if idx == eos_idx:
            eos_pos = i
            break
    seq = [
        idx for idx in seq[:eos_pos + 1]
        if (output_bos or idx != bos_idx) and (output_eos or idx != eos_idx)
    ]
    return seq


def do_predict(args):
G
guosheng 已提交
54 55 56 57
    device = set_device("gpu" if args.use_cuda else "cpu")
    fluid.enable_dygraph(device) if args.eager_run else None

    inputs = [
G
guosheng 已提交
58 59 60 61 62 63 64 65 66 67 68 69
        Input(
            [None, None], "int64", name="src_word"),
        Input(
            [None, None], "int64", name="src_pos"),
        Input(
            [None, args.n_head, None, None],
            "float32",
            name="src_slf_attn_bias"),
        Input(
            [None, args.n_head, None, None],
            "float32",
            name="trg_src_attn_bias"),
G
guosheng 已提交
70 71 72
    ]

    # define data
G
guosheng 已提交
73 74 75 76 77 78 79 80
    dataset = Seq2SeqDataset(
        fpattern=args.predict_file,
        src_vocab_fpath=args.src_vocab_fpath,
        trg_vocab_fpath=args.trg_vocab_fpath,
        token_delimiter=args.token_delimiter,
        start_mark=args.special_token[0],
        end_mark=args.special_token[1],
        unk_mark=args.special_token[2])
G
guosheng 已提交
81
    args.src_vocab_size, args.trg_vocab_size, args.bos_idx, args.eos_idx, \
G
guosheng 已提交
82
        args.unk_idx = dataset.get_vocab_summary()
G
guosheng 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    trg_idx2word = Seq2SeqDataset.load_dict(
        dict_path=args.trg_vocab_fpath, reverse=True)
    batch_sampler = Seq2SeqBatchSampler(
        dataset=dataset,
        use_token_batch=False,
        batch_size=args.batch_size,
        max_length=args.max_length)
    data_loader = DataLoader(
        dataset=dataset,
        batch_sampler=batch_sampler,
        places=device,
        collate_fn=partial(
            prepare_infer_input, src_pad_idx=args.eos_idx, n_head=args.n_head),
        num_workers=0,
        return_list=True)
G
guosheng 已提交
98 99

    # define model
G
guosheng 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    transformer = InferTransformer(
        args.src_vocab_size,
        args.trg_vocab_size,
        args.max_length + 1,
        args.n_layer,
        args.n_head,
        args.d_key,
        args.d_value,
        args.d_model,
        args.d_inner_hid,
        args.prepostprocess_dropout,
        args.attention_dropout,
        args.relu_dropout,
        args.preprocess_cmd,
        args.postprocess_cmd,
        args.weight_sharing,
        args.bos_idx,
        args.eos_idx,
        beam_size=args.beam_size,
        max_out_len=args.max_out_len)
G
guosheng 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    transformer.prepare(inputs=inputs)

    # load the trained model
    assert args.init_from_params, (
        "Please set init_from_params to load the infer model.")
    transformer.load(os.path.join(args.init_from_params, "transformer"))

    # TODO: use model.predict when support variant length
    f = open(args.output_file, "wb")
    for data in data_loader():
        finished_seq = transformer.test(inputs=flatten(data))[0]
        finished_seq = np.transpose(finished_seq, [0, 2, 1])
        for ins in finished_seq:
            for beam_idx, beam in enumerate(ins):
                if beam_idx >= args.n_best: break
G
guosheng 已提交
135
                id_list = post_process_seq(beam, args.bos_idx, args.eos_idx)
G
guosheng 已提交
136 137 138
                word_list = [trg_idx2word[id] for id in id_list]
                sequence = b" ".join(word_list) + b"\n"
                f.write(sequence)
G
guosheng 已提交
139 140 141 142 143 144 145 146 147 148


if __name__ == "__main__":
    args = PDConfig(yaml_file="./transformer.yaml")
    args.build()
    args.Print()
    check_gpu(args.use_cuda)
    check_version()

    do_predict(args)