test_rnn_encoder_decoder.py 11.1 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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 numpy as np
16
import paddle
17 18
import paddle.fluid as fluid
import paddle.fluid.framework as framework
19
import contextlib
20 21
import math
import sys
22
import os
23
import unittest
24
import tempfile
25
from paddle.fluid.executor import Executor
P
pangyoki 已提交
26 27 28
import paddle

paddle.enable_static()
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

dict_size = 30000
source_dict_dim = target_dict_dim = dict_size
src_dict, trg_dict = paddle.dataset.wmt14.get_dict(dict_size)
hidden_dim = 32
embedding_dim = 16
batch_size = 10
max_length = 50
topk_size = 50
encoder_size = decoder_size = hidden_dim
IS_SPARSE = True
USE_PEEPHOLES = False


def bi_lstm_encoder(input_seq, hidden_size):
    input_forward_proj = fluid.layers.fc(input=input_seq,
                                         size=hidden_size * 4,
                                         bias_attr=True)
47 48 49
    forward, _ = fluid.layers.dynamic_lstm(input=input_forward_proj,
                                           size=hidden_size * 4,
                                           use_peepholes=USE_PEEPHOLES)
50 51 52
    input_backward_proj = fluid.layers.fc(input=input_seq,
                                          size=hidden_size * 4,
                                          bias_attr=True)
53 54 55 56
    backward, _ = fluid.layers.dynamic_lstm(input=input_backward_proj,
                                            size=hidden_size * 4,
                                            is_reverse=True,
                                            use_peepholes=USE_PEEPHOLES)
P
peterzhang2029 已提交
57 58 59 60 61

    forward_last = fluid.layers.sequence_last_step(input=forward)
    backward_first = fluid.layers.sequence_first_step(input=backward)

    return forward_last, backward_first
62 63 64 65


# FIXME(peterzhang2029): Replace this function with the lstm_unit_op.
def lstm_step(x_t, hidden_t_prev, cell_t_prev, size):
66

67 68 69 70 71 72 73 74 75
    def linear(inputs):
        return fluid.layers.fc(input=inputs, size=size, bias_attr=True)

    forget_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
    input_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
    output_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
    cell_tilde = fluid.layers.tanh(x=linear([hidden_t_prev, x_t]))

    cell_t = fluid.layers.sums(input=[
76 77
        fluid.layers.elementwise_mul(x=forget_gate, y=cell_t_prev),
        fluid.layers.elementwise_mul(x=input_gate, y=cell_tilde)
78 79
    ])

80 81
    hidden_t = fluid.layers.elementwise_mul(x=output_gate,
                                            y=fluid.layers.tanh(x=cell_t))
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

    return hidden_t, cell_t


def lstm_decoder_without_attention(target_embedding, decoder_boot, context,
                                   decoder_size):
    rnn = fluid.layers.DynamicRNN()

    cell_init = fluid.layers.fill_constant_batch_size_like(
        input=decoder_boot,
        value=0.0,
        shape=[-1, decoder_size],
        dtype='float32')
    cell_init.stop_gradient = False

    with rnn.block():
        current_word = rnn.step_input(target_embedding)
        context = rnn.static_input(context)

        hidden_mem = rnn.memory(init=decoder_boot, need_reorder=True)
        cell_mem = rnn.memory(init=cell_init)
103 104
        decoder_inputs = fluid.layers.concat(input=[context, current_word],
                                             axis=1)
105 106 107 108 109 110 111 112 113 114 115 116 117 118
        h, c = lstm_step(decoder_inputs, hidden_mem, cell_mem, decoder_size)
        rnn.update_memory(hidden_mem, h)
        rnn.update_memory(cell_mem, c)
        out = fluid.layers.fc(input=h,
                              size=target_dict_dim,
                              bias_attr=True,
                              act='softmax')
        rnn.output(out)
    return rnn()


def seq_to_seq_net():
    """Construct a seq2seq network."""

119 120 121 122
    src_word_idx = fluid.layers.data(name='source_sequence',
                                     shape=[1],
                                     dtype='int64',
                                     lod_level=1)
123 124 125 126 127 128

    src_embedding = fluid.layers.embedding(
        input=src_word_idx,
        size=[source_dict_dim, embedding_dim],
        dtype='float32')

P
peterzhang2029 已提交
129
    src_forward_last, src_backward_first = bi_lstm_encoder(
130 131
        input_seq=src_embedding, hidden_size=encoder_size)

P
peterzhang2029 已提交
132 133
    encoded_vector = fluid.layers.concat(
        input=[src_forward_last, src_backward_first], axis=1)
134

P
peterzhang2029 已提交
135
    decoder_boot = fluid.layers.fc(input=src_backward_first,
136 137 138 139
                                   size=decoder_size,
                                   bias_attr=False,
                                   act='tanh')

140 141 142 143
    trg_word_idx = fluid.layers.data(name='target_sequence',
                                     shape=[1],
                                     dtype='int64',
                                     lod_level=1)
144 145 146 147 148 149 150

    trg_embedding = fluid.layers.embedding(
        input=trg_word_idx,
        size=[target_dict_dim, embedding_dim],
        dtype='float32')

    prediction = lstm_decoder_without_attention(trg_embedding, decoder_boot,
P
peterzhang2029 已提交
151
                                                encoded_vector, decoder_size)
152 153 154 155
    label = fluid.layers.data(name='label_sequence',
                              shape=[1],
                              dtype='int64',
                              lod_level=1)
156
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
157
    avg_cost = paddle.mean(cost)
158

K
Kexin Zhao 已提交
159
    return avg_cost, prediction
160 161


162
def train(use_cuda, save_dirname=None):
K
Kexin Zhao 已提交
163
    [avg_cost, prediction] = seq_to_seq_net()
164 165 166 167

    optimizer = fluid.optimizer.Adagrad(learning_rate=1e-4)
    optimizer.minimize(avg_cost)

168 169 170
    train_data = paddle.batch(paddle.reader.shuffle(
        paddle.dataset.wmt14.train(dict_size), buf_size=1000),
                              batch_size=batch_size)
171

172
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
173 174 175
    exe = Executor(place)
    exe.run(framework.default_startup_program())

176 177 178 179 180 181 182
    feed_order = ['source_sequence', 'target_sequence', 'label_sequence']
    feed_list = [
        framework.default_main_program().global_block().var(var_name)
        for var_name in feed_order
    ]
    feeder = fluid.DataFeeder(feed_list, place)

183
    batch_id = 0
184
    for pass_id in range(2):
185 186
        for data in train_data():
            outs = exe.run(framework.default_main_program(),
187
                           feed=feeder.feed(data),
188
                           fetch_list=[avg_cost])
189

190
            avg_cost_val = np.array(outs[0])
191 192
            print('pass_id=' + str(pass_id) + ' batch=' + str(batch_id) +
                  " avg_cost=" + str(avg_cost_val))
193 194
            if math.isnan(float(avg_cost_val[0])):
                sys.exit("got NaN loss, training failed.")
195
            if batch_id > 3:
K
Kexin Zhao 已提交
196
                if save_dirname is not None:
197
                    fluid.io.save_inference_model(
198 199
                        save_dirname, ['source_sequence', 'target_sequence'],
                        [prediction], exe)
200 201
                return

202 203 204
            batch_id += 1


205
def infer(use_cuda, save_dirname=None):
K
Kexin Zhao 已提交
206 207 208
    if save_dirname is None:
        return

209
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
K
Kexin Zhao 已提交
210 211
    exe = fluid.Executor(place)

212 213 214
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
T
tianshuo78520a 已提交
215
        # the feed_target_names (the names of variables that will be fed
216 217 218 219 220
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
        [inference_program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(save_dirname, exe)

221
        # Setup input by creating LoDTensor to represent sequence of words.
222 223
        # Here each word is the basic element of the LoDTensor and the shape of
        # each word (base_shape) should be [1] since it is simply an index to
224
        # look up for the corresponding word vector.
225
        # Suppose the recursive_sequence_lengths info is set to [[4, 6]],
226 227 228 229
        # which has only one level of detail. Then the created LoDTensor will have only
        # one higher level structure (sequence of words, or sentence) than the basic
        # element (word). Hence the LoDTensor will hold data for two sentences of
        # length 4 and 6, respectively.
230 231
        # Note that recursive_sequence_lengths should be a list of lists.
        recursive_seq_lens = [[4, 6]]
232 233
        base_shape = [1]
        # The range of random integers is [low, high]
234 235 236 237 238 239 240 241 242 243
        word_data = fluid.create_random_int_lodtensor(recursive_seq_lens,
                                                      base_shape,
                                                      place,
                                                      low=0,
                                                      high=1)
        trg_word = fluid.create_random_int_lodtensor(recursive_seq_lens,
                                                     base_shape,
                                                     place,
                                                     low=0,
                                                     high=1)
244 245 246 247 248 249 250 251 252 253 254 255

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
        assert feed_target_names[0] == 'source_sequence'
        assert feed_target_names[1] == 'target_sequence'
        results = exe.run(inference_program,
                          feed={
                              feed_target_names[0]: word_data,
                              feed_target_names[1]: trg_word,
                          },
                          fetch_list=fetch_targets,
                          return_numpy=False)
256
        print(results[0].recursive_sequence_lengths())
257
        np_data = np.array(results[0])
258 259
        print("Inference shape: ", np_data.shape)
        print("Inference results: ", np_data)
K
Kexin Zhao 已提交
260 261


262 263 264 265 266
def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the trained model
267 268 269
    temp_dir = tempfile.TemporaryDirectory()
    save_dirname = os.path.join(temp_dir.name,
                                "rnn_encoder_decoder.inference.model")
270 271 272

    train(use_cuda, save_dirname)
    infer(use_cuda, save_dirname)
273
    temp_dir.cleanup()
274 275 276


class TestRnnEncoderDecoder(unittest.TestCase):
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    def test_cuda(self):
        with self.scope_prog_guard():
            main(use_cuda=True)

    def test_cpu(self):
        with self.scope_prog_guard():
            main(use_cuda=False)

    @contextlib.contextmanager
    def scope_prog_guard(self):
        prog = fluid.Program()
        startup_prog = fluid.Program()
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
            with fluid.program_guard(prog, startup_prog):
                yield


296
if __name__ == '__main__':
297
    unittest.main()