test_rnn_decode_api.py 30.0 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
G
Guo Sheng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

15
import random
G
Guo Sheng 已提交
16
import unittest
17

18
import numpy as np
G
Guo Sheng 已提交
19

20
import paddle
21 22 23
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.layers as layers
24 25 26
import paddle.nn as nn
from paddle import Model, set_device
from paddle.fluid.dygraph import Layer
G
Guo Sheng 已提交
27
from paddle.fluid.executor import Executor
28
from paddle.fluid.framework import _test_eager_guard
29 30
from paddle.nn import BeamSearchDecoder, dynamic_decode
from paddle.static import InputSpec as Input
31

32 33
paddle.enable_static()

G
Guo Sheng 已提交
34

35
class EncoderCell(layers.RNNCell):
36
    def __init__(self, num_layers, hidden_size, dropout_prob=0.0):
G
Guo Sheng 已提交
37 38 39
        self.num_layers = num_layers
        self.hidden_size = hidden_size
        self.dropout_prob = dropout_prob
40 41 42
        self.lstm_cells = [
            layers.LSTMCell(hidden_size) for i in range(num_layers)
        ]
G
Guo Sheng 已提交
43 44 45 46 47

    def call(self, step_input, states):
        new_states = []
        for i in range(self.num_layers):
            out, new_state = self.lstm_cells[i](step_input, states[i])
48 49 50 51 52
            step_input = (
                layers.dropout(out, self.dropout_prob)
                if self.dropout_prob > 0
                else out
            )
G
Guo Sheng 已提交
53 54 55 56 57 58 59 60
            new_states.append(new_state)
        return step_input, new_states

    @property
    def state_shape(self):
        return [cell.state_shape for cell in self.lstm_cells]


61
class DecoderCell(layers.RNNCell):
62
    def __init__(self, num_layers, hidden_size, dropout_prob=0.0):
G
Guo Sheng 已提交
63 64 65
        self.num_layers = num_layers
        self.hidden_size = hidden_size
        self.dropout_prob = dropout_prob
66 67 68
        self.lstm_cells = [
            layers.LSTMCell(hidden_size) for i in range(num_layers)
        ]
G
Guo Sheng 已提交
69 70

    def attention(self, hidden, encoder_output, encoder_padding_mask):
71 72 73 74 75 76
        query = layers.fc(
            hidden, size=encoder_output.shape[-1], bias_attr=False
        )
        attn_scores = layers.matmul(
            layers.unsqueeze(query, [1]), encoder_output, transpose_y=True
        )
G
Guo Sheng 已提交
77
        if encoder_padding_mask is not None:
78
            attn_scores = paddle.add(attn_scores, encoder_padding_mask)
G
Guo Sheng 已提交
79
        attn_scores = layers.softmax(attn_scores)
80
        attn_out = paddle.squeeze(
81 82
            layers.matmul(attn_scores, encoder_output), [1]
        )
G
Guo Sheng 已提交
83 84 85 86
        attn_out = layers.concat([attn_out, hidden], 1)
        attn_out = layers.fc(attn_out, size=self.hidden_size, bias_attr=False)
        return attn_out

87 88 89
    def call(
        self, step_input, states, encoder_output, encoder_padding_mask=None
    ):
G
Guo Sheng 已提交
90 91 92 93 94
        lstm_states, input_feed = states
        new_lstm_states = []
        step_input = layers.concat([step_input, input_feed], 1)
        for i in range(self.num_layers):
            out, new_lstm_state = self.lstm_cells[i](step_input, lstm_states[i])
95 96 97 98 99
            step_input = (
                layers.dropout(out, self.dropout_prob)
                if self.dropout_prob > 0
                else out
            )
G
Guo Sheng 已提交
100 101 102 103 104
            new_lstm_states.append(new_lstm_state)
        out = self.attention(step_input, encoder_output, encoder_padding_mask)
        return out, [new_lstm_states, out]


105
class Encoder:
106
    def __init__(self, num_layers, hidden_size, dropout_prob=0.0):
107
        self.encoder_cell = EncoderCell(num_layers, hidden_size, dropout_prob)
G
Guo Sheng 已提交
108

109 110 111 112 113
    def __call__(self, src_emb, src_sequence_length):
        encoder_output, encoder_final_state = layers.rnn(
            cell=self.encoder_cell,
            inputs=src_emb,
            sequence_length=src_sequence_length,
114 115
            is_reverse=False,
        )
116 117 118
        return encoder_output, encoder_final_state


119
class Decoder:
120 121 122 123 124 125 126 127
    def __init__(
        self,
        num_layers,
        hidden_size,
        dropout_prob,
        decoding_strategy="infer_sample",
        max_decoding_length=20,
    ):
128 129
        self.decoder_cell = DecoderCell(num_layers, hidden_size, dropout_prob)
        self.decoding_strategy = decoding_strategy
130 131 132 133 134 135 136 137 138 139 140 141 142
        self.max_decoding_length = (
            None
            if (self.decoding_strategy == "train_greedy")
            else max_decoding_length
        )

    def __call__(
        self,
        decoder_initial_states,
        encoder_output,
        encoder_padding_mask,
        **kwargs
    ):
143 144 145 146 147 148 149 150 151 152 153
        output_layer = kwargs.pop("output_layer", None)
        if self.decoding_strategy == "train_greedy":
            # for teach-forcing MLE pre-training
            helper = layers.TrainingHelper(**kwargs)
        elif self.decoding_strategy == "infer_sample":
            helper = layers.SampleEmbeddingHelper(**kwargs)
        elif self.decoding_strategy == "infer_greedy":
            helper = layers.GreedyEmbeddingHelper(**kwargs)

        if self.decoding_strategy == "beam_search":
            beam_size = kwargs.get("beam_size", 4)
154 155 156 157 158 159 160 161 162 163 164 165 166
            encoder_output = (
                layers.BeamSearchDecoder.tile_beam_merge_with_batch(
                    encoder_output, beam_size
                )
            )
            encoder_padding_mask = (
                layers.BeamSearchDecoder.tile_beam_merge_with_batch(
                    encoder_padding_mask, beam_size
                )
            )
            decoder = layers.BeamSearchDecoder(
                cell=self.decoder_cell, output_fn=output_layer, **kwargs
            )
167
        else:
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
            decoder = layers.BasicDecoder(
                self.decoder_cell, helper, output_fn=output_layer
            )

        (
            decoder_output,
            decoder_final_state,
            dec_seq_lengths,
        ) = layers.dynamic_decode(
            decoder,
            inits=decoder_initial_states,
            max_step_num=self.max_decoding_length,
            encoder_output=encoder_output,
            encoder_padding_mask=encoder_padding_mask,
            impute_finished=False  # for test coverage
            if self.decoding_strategy == "beam_search"
            else True,
            is_test=True if self.decoding_strategy == "beam_search" else False,
            return_length=True,
        )
188 189 190
        return decoder_output, decoder_final_state, dec_seq_lengths


191
class Seq2SeqModel:
192 193
    """Seq2Seq model: RNN encoder-decoder with attention"""

194 195 196 197 198 199 200 201 202 203 204 205 206
    def __init__(
        self,
        num_layers,
        hidden_size,
        dropout_prob,
        src_vocab_size,
        trg_vocab_size,
        start_token,
        end_token,
        decoding_strategy="infer_sample",
        max_decoding_length=20,
        beam_size=4,
    ):
207
        self.start_token, self.end_token = start_token, end_token
208 209 210 211
        self.max_decoding_length, self.beam_size = (
            max_decoding_length,
            beam_size,
        )
J
Jiaqi Liu 已提交
212 213 214
        self.src_embeder = paddle.nn.Embedding(
            src_vocab_size,
            hidden_size,
215 216
            weight_attr=fluid.ParamAttr(name="source_embedding"),
        )
J
Jiaqi Liu 已提交
217 218 219
        self.trg_embeder = paddle.nn.Embedding(
            trg_vocab_size,
            hidden_size,
220 221
            weight_attr=fluid.ParamAttr(name="target_embedding"),
        )
222
        self.encoder = Encoder(num_layers, hidden_size, dropout_prob)
223 224 225 226 227 228 229 230 231 232 233 234 235 236
        self.decoder = Decoder(
            num_layers,
            hidden_size,
            dropout_prob,
            decoding_strategy,
            max_decoding_length,
        )
        self.output_layer = lambda x: layers.fc(
            x,
            size=trg_vocab_size,
            num_flatten_dims=len(x.shape) - 1,
            param_attr=fluid.ParamAttr(),
            bias_attr=False,
        )
G
Guo Sheng 已提交
237

238 239 240
    def __call__(self, src, src_length, trg=None, trg_length=None):
        # encoder
        encoder_output, encoder_final_state = self.encoder(
241 242
            self.src_embeder(src), src_length
        )
G
Guo Sheng 已提交
243 244

        decoder_initial_states = [
245 246
            encoder_final_state,
            self.decoder.decoder_cell.get_initial_states(
247 248
                batch_ref=encoder_output, shape=[encoder_output.shape[-1]]
            ),
G
Guo Sheng 已提交
249
        ]
250 251 252
        src_mask = layers.sequence_mask(
            src_length, maxlen=layers.shape(src)[1], dtype="float32"
        )
253 254
        encoder_padding_mask = (src_mask - 1.0) * 1e9
        encoder_padding_mask = layers.unsqueeze(encoder_padding_mask, [1])
G
Guo Sheng 已提交
255

256
        # decoder
257
        decoder_kwargs = (
258
            {
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
                "inputs": self.trg_embeder(trg),
                "sequence_length": trg_length,
            }
            if self.decoder.decoding_strategy == "train_greedy"
            else (
                {
                    "embedding_fn": self.trg_embeder,
                    "beam_size": self.beam_size,
                    "start_token": self.start_token,
                    "end_token": self.end_token,
                }
                if self.decoder.decoding_strategy == "beam_search"
                else {
                    "embedding_fn": self.trg_embeder,
                    "start_tokens": layers.fill_constant_batch_size_like(
                        input=encoder_output,
                        shape=[-1],
                        dtype=src.dtype,
                        value=self.start_token,
                    ),
                    "end_token": self.end_token,
                }
            )
        )
283 284
        decoder_kwargs["output_layer"] = self.output_layer

285 286 287 288 289 290
        (decoder_output, decoder_final_state, dec_seq_lengths) = self.decoder(
            decoder_initial_states,
            encoder_output,
            encoder_padding_mask,
            **decoder_kwargs
        )
291 292
        if self.decoder.decoding_strategy == "beam_search":  # for inference
            return decoder_output
293 294 295 296 297
        logits, samples, sample_length = (
            decoder_output.cell_outputs,
            decoder_output.sample_ids,
            dec_seq_lengths,
        )
298 299 300 301
        probs = layers.softmax(logits)
        return probs, samples, sample_length


302
class PolicyGradient:
303 304 305 306 307 308 309 310 311
    """policy gradient"""

    def __init__(self, lr=None):
        self.lr = lr

    def learn(self, act_prob, action, reward, length=None):
        """
        update policy model self.model with policy gradient algorithm
        """
312 313 314
        self.reward = fluid.layers.py_func(
            func=reward_func, x=[action, length], out=reward
        )
315 316
        neg_log_prob = layers.cross_entropy(act_prob, action)
        cost = neg_log_prob * reward
317
        cost = (
318
            (paddle.sum(cost) / paddle.sum(length))
319
            if length is not None
320
            else paddle.mean(cost)
321
        )
322 323 324 325 326 327 328 329
        optimizer = fluid.optimizer.Adam(self.lr)
        optimizer.minimize(cost)
        return cost


def reward_func(samples, sample_length):
    """toy reward"""

330
    def discount_reward(reward, sequence_length, discount=1.0):
331 332
        return discount_reward_1d(reward, sequence_length, discount)

333
    def discount_reward_1d(reward, sequence_length, discount=1.0, dtype=None):
334 335
        if sequence_length is None:
            raise ValueError(
336 337
                'sequence_length must not be `None` for 1D reward.'
            )
338 339 340 341 342
        reward = np.array(reward)
        sequence_length = np.array(sequence_length)
        batch_size = reward.shape[0]
        max_seq_length = np.max(sequence_length)
        dtype = dtype or reward.dtype
343
        if discount == 1.0:
344
            dmat = np.ones([batch_size, max_seq_length], dtype=dtype)
G
Guo Sheng 已提交
345
        else:
346
            steps = np.tile(np.arange(max_seq_length), [batch_size, 1])
347 348 349
            mask = np.asarray(
                steps < (sequence_length - 1)[:, None], dtype=dtype
            )
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
            # Make each row = [discount, ..., discount, 1, ..., 1]
            dmat = mask * discount + (1 - mask)
            dmat = np.cumprod(dmat[:, ::-1], axis=1)[:, ::-1]
        disc_reward = dmat * reward[:, None]
        disc_reward = mask_sequences(disc_reward, sequence_length, dtype=dtype)
        return disc_reward

    def mask_sequences(sequence, sequence_length, dtype=None, time_major=False):
        sequence = np.array(sequence)
        sequence_length = np.array(sequence_length)
        rank = sequence.ndim
        if rank < 2:
            raise ValueError("`sequence` must be 2D or higher order.")
        batch_size = sequence.shape[0]
        max_time = sequence.shape[1]
        dtype = dtype or sequence.dtype
        if time_major:
            sequence = np.transpose(sequence, axes=[1, 0, 2])
        steps = np.tile(np.arange(max_time), [batch_size, 1])
        mask = np.asarray(steps < sequence_length[:, None], dtype=dtype)
        for _ in range(2, rank):
            mask = np.expand_dims(mask, -1)
        sequence = sequence * mask
        if time_major:
            sequence = np.transpose(sequence, axes=[1, 0, 2])
        return sequence

    samples = np.array(samples)
    sample_length = np.array(sample_length)
    # length reward
    reward = (5 - np.abs(sample_length - 5)).astype("float32")
    # repeat punishment to trapped into local minima getting all same words
    # beam search to get more than one sample may also can avoid this
    for i in range(reward.shape[0]):
384 385 386 387 388 389 390 391 392
        reward[i] += (
            -10
            if sample_length[i] > 1
            and np.all(samples[i][: sample_length[i] - 1] == samples[i][0])
            else 0
        )
    return discount_reward(reward, sample_length, discount=1.0).astype(
        "float32"
    )
393 394


395
class MLE:
396 397 398 399 400 401 402 403 404 405
    """teacher-forcing MLE training"""

    def __init__(self, lr=None):
        self.lr = lr

    def learn(self, probs, label, weight=None, length=None):
        loss = layers.cross_entropy(input=probs, label=label, soft_label=False)
        max_seq_len = layers.shape(probs)[1]
        mask = layers.sequence_mask(length, maxlen=max_seq_len, dtype="float32")
        loss = loss * mask
406
        loss = paddle.mean(loss, axis=[0])
407
        loss = paddle.sum(loss)
408 409 410 411 412
        optimizer = fluid.optimizer.Adam(self.lr)
        optimizer.minimize(loss)
        return loss


413
class SeqPGAgent:
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    def __init__(
        self,
        model_cls,
        alg_cls=PolicyGradient,
        model_hparams={},
        alg_hparams={},
        executor=None,
        main_program=None,
        startup_program=None,
        seed=None,
    ):
        self.main_program = (
            fluid.Program() if main_program is None else main_program
        )
        self.startup_program = (
            fluid.Program() if startup_program is None else startup_program
        )
431 432 433 434 435 436 437 438 439
        if seed is not None:
            self.main_program.random_seed = seed
            self.startup_program.random_seed = seed
        self.build_program(model_cls, alg_cls, model_hparams, alg_hparams)
        self.executor = executor

    def build_program(self, model_cls, alg_cls, model_hparams, alg_hparams):
        with fluid.program_guard(self.main_program, self.startup_program):
            source = fluid.data(name="src", shape=[None, None], dtype="int64")
440 441 442
            source_length = fluid.data(
                name="src_sequence_length", shape=[None], dtype="int64"
            )
443 444
            # only for teacher-forcing MLE training
            target = fluid.data(name="trg", shape=[None, None], dtype="int64")
445 446 447 448 449 450
            target_length = fluid.data(
                name="trg_sequence_length", shape=[None], dtype="int64"
            )
            label = fluid.data(
                name="label", shape=[None, None, 1], dtype="int64"
            )
451 452 453
            self.model = model_cls(**model_hparams)
            self.alg = alg_cls(**alg_hparams)
            self.probs, self.samples, self.sample_length = self.model(
454 455
                source, source_length, target, target_length
            )
456
            self.samples.stop_gradient = True
457
            self.reward = fluid.data(
458
                name="reward",
459
                shape=[None, None],  # batch_size, seq_len
460 461
                dtype=self.probs.dtype,
            )
462
            self.samples.stop_gradient = False
463 464 465
            self.cost = self.alg.learn(
                self.probs, self.samples, self.reward, self.sample_length
            )
466 467 468 469

        # to define the same parameters between different programs
        self.pred_program = self.main_program._prune_with_input(
            [source.name, source_length.name],
470 471
            [self.probs, self.samples, self.sample_length],
        )
472 473 474 475 476

    def predict(self, feed_dict):
        samples, sample_length = self.executor.run(
            self.pred_program,
            feed=feed_dict,
477 478
            fetch_list=[self.samples, self.sample_length],
        )
479 480 481
        return samples, sample_length

    def learn(self, feed_dict, fetch_list):
482 483 484
        results = self.executor.run(
            self.main_program, feed=feed_dict, fetch_list=fetch_list
        )
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        return results


class TestDynamicDecode(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.model_hparams = {
            "num_layers": 2,
            "hidden_size": 32,
            "dropout_prob": 0.1,
            "src_vocab_size": 100,
            "trg_vocab_size": 100,
            "start_token": 0,
            "end_token": 1,
            "decoding_strategy": "infer_greedy",
500
            "max_decoding_length": 10,
501 502 503 504 505 506 507
        }

        self.iter_num = iter_num = 2
        self.batch_size = batch_size = 4
        src_seq_len = 10
        trg_seq_len = 12
        self.data = {
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
            "src": np.random.randint(
                2,
                self.model_hparams["src_vocab_size"],
                (iter_num * batch_size, src_seq_len),
            ).astype("int64"),
            "src_sequence_length": np.random.randint(
                1, src_seq_len, (iter_num * batch_size,)
            ).astype("int64"),
            "trg": np.random.randint(
                2,
                self.model_hparams["src_vocab_size"],
                (iter_num * batch_size, trg_seq_len),
            ).astype("int64"),
            "trg_sequence_length": np.random.randint(
                1, trg_seq_len, (iter_num * batch_size,)
            ).astype("int64"),
            "label": np.random.randint(
                2,
                self.model_hparams["src_vocab_size"],
                (iter_num * batch_size, trg_seq_len, 1),
            ).astype("int64"),
529 530
        }

531 532 533 534 535
        place = (
            core.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else core.CPUPlace()
        )
536 537 538
        self.exe = Executor(place)

    def test_mle_train(self):
539
        paddle.enable_static()
540
        self.model_hparams["decoding_strategy"] = "train_greedy"
541 542 543 544 545 546 547 548 549 550
        agent = SeqPGAgent(
            model_cls=Seq2SeqModel,
            alg_cls=MLE,
            model_hparams=self.model_hparams,
            alg_hparams={"lr": 0.001},
            executor=self.exe,
            main_program=fluid.Program(),
            startup_program=fluid.Program(),
            seed=123,
        )
551 552 553 554
        self.exe.run(agent.startup_program)
        for iter_idx in range(self.iter_num):
            reward, cost = agent.learn(
                {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                    "src": self.data["src"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size,
                        :,
                    ],
                    "src_sequence_length": self.data["src_sequence_length"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
                    "trg": self.data["trg"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size,
                        :,
                    ],
                    "trg_sequence_length": self.data["trg_sequence_length"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
                    "label": self.data["label"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
582
                },
583 584 585 586 587 588
                fetch_list=[agent.cost, agent.cost],
            )
            print(
                "iter_idx: %d, reward: %f, cost: %f"
                % (iter_idx, reward.mean(), cost)
            )
589 590

    def test_greedy_train(self):
591
        paddle.enable_static()
592
        self.model_hparams["decoding_strategy"] = "infer_greedy"
593 594 595 596 597 598 599 600 601 602
        agent = SeqPGAgent(
            model_cls=Seq2SeqModel,
            alg_cls=PolicyGradient,
            model_hparams=self.model_hparams,
            alg_hparams={"lr": 0.001},
            executor=self.exe,
            main_program=fluid.Program(),
            startup_program=fluid.Program(),
            seed=123,
        )
603 604 605 606
        self.exe.run(agent.startup_program)
        for iter_idx in range(self.iter_num):
            reward, cost = agent.learn(
                {
607 608 609 610 611 612 613 614 615 616 617
                    "src": self.data["src"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size,
                        :,
                    ],
                    "src_sequence_length": self.data["src_sequence_length"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
618
                },
619 620 621 622 623 624
                fetch_list=[agent.reward, agent.cost],
            )
            print(
                "iter_idx: %d, reward: %f, cost: %f"
                % (iter_idx, reward.mean(), cost)
            )
625 626

    def test_sample_train(self):
627
        paddle.enable_static()
628
        self.model_hparams["decoding_strategy"] = "infer_sample"
629 630 631 632 633 634 635 636 637 638
        agent = SeqPGAgent(
            model_cls=Seq2SeqModel,
            alg_cls=PolicyGradient,
            model_hparams=self.model_hparams,
            alg_hparams={"lr": 0.001},
            executor=self.exe,
            main_program=fluid.Program(),
            startup_program=fluid.Program(),
            seed=123,
        )
639 640 641 642
        self.exe.run(agent.startup_program)
        for iter_idx in range(self.iter_num):
            reward, cost = agent.learn(
                {
643 644 645 646 647 648 649 650 651 652 653
                    "src": self.data["src"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size,
                        :,
                    ],
                    "src_sequence_length": self.data["src_sequence_length"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
654
                },
655 656 657 658 659 660
                fetch_list=[agent.reward, agent.cost],
            )
            print(
                "iter_idx: %d, reward: %f, cost: %f"
                % (iter_idx, reward.mean(), cost)
            )
661 662

    def test_beam_search_infer(self):
663 664
        paddle.set_default_dtype("float32")
        paddle.enable_static()
665 666 667 668 669
        self.model_hparams["decoding_strategy"] = "beam_search"
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            source = fluid.data(name="src", shape=[None, None], dtype="int64")
670 671 672
            source_length = fluid.data(
                name="src_sequence_length", shape=[None], dtype="int64"
            )
673 674 675 676 677 678 679 680
            model = Seq2SeqModel(**self.model_hparams)
            output = model(source, source_length)

        self.exe.run(startup_program)
        for iter_idx in range(self.iter_num):
            trans_ids = self.exe.run(
                program=main_program,
                feed={
681 682 683 684 685 686 687 688 689 690 691
                    "src": self.data["src"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size,
                        :,
                    ],
                    "src_sequence_length": self.data["src_sequence_length"][
                        iter_idx
                        * self.batch_size : (iter_idx + 1)
                        * self.batch_size
                    ],
692
                },
693 694
                fetch_list=[output],
            )[0]
G
Guo Sheng 已提交
695

696
    def func_dynamic_basic_decoder(self):
J
Jiaqi Liu 已提交
697 698 699 700 701 702 703
        paddle.disable_static()
        src = paddle.to_tensor(np.random.randint(8, size=(8, 4)))
        src_length = paddle.to_tensor(np.random.randint(8, size=(8)))
        model = Seq2SeqModel(**self.model_hparams)
        probs, samples, sample_length = model(src, src_length)
        paddle.enable_static()

704 705 706 707 708
    def test_dynamic_basic_decoder(self):
        with _test_eager_guard():
            self.func_dynamic_basic_decoder()
        self.func_dynamic_basic_decoder()

G
Guo Sheng 已提交
709

710 711 712 713 714 715 716 717 718
class ModuleApiTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._np_rand_state = np.random.get_state()
        cls._py_rand_state = random.getstate()
        cls._random_seed = 123
        np.random.seed(cls._random_seed)
        random.seed(cls._random_seed)

719
        cls.model_cls = type(
720 721 722
            cls.__name__ + "Model",
            (Layer,),
            {
723
                "__init__": cls.model_init_wrapper(cls.model_init),
724 725 726
                "forward": cls.model_forward,
            },
        )
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

    @classmethod
    def tearDownClass(cls):
        np.random.set_state(cls._np_rand_state)
        random.setstate(cls._py_rand_state)

    @staticmethod
    def model_init_wrapper(func):
        def __impl__(self, *args, **kwargs):
            Layer.__init__(self)
            func(self, *args, **kwargs)

        return __impl__

    @staticmethod
    def model_init(model, *args, **kwargs):
        raise NotImplementedError(
744 745
            "model_init acts as `Model.__init__`, thus must implement it"
        )
746 747 748 749 750 751 752 753

    @staticmethod
    def model_forward(model, *args, **kwargs):
        return model.module(*args, **kwargs)

    def make_inputs(self):
        # TODO(guosheng): add default from `self.inputs`
        raise NotImplementedError(
754 755
            "model_inputs makes inputs for model, thus must implement it"
        )
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

    def setUp(self):
        """
        For the model which wraps the module to be tested:
            Set input data by `self.inputs` list
            Set init argument values by `self.attrs` list/dict
            Set model parameter values by `self.param_states` dict
            Set expected output data by `self.outputs` list
        We can create a model instance and run once with these.
        """
        self.inputs = []
        self.attrs = {}
        self.param_states = {}
        self.outputs = []

    def _calc_output(self, place, mode="test", dygraph=True):
        if dygraph:
            fluid.enable_dygraph(place)
        else:
            fluid.disable_dygraph()
C
cnn 已提交
776
        gen = paddle.seed(self._random_seed)
777 778 779
        paddle.framework.random._manual_program_seed(self._random_seed)
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
780 781 782 783 784
            layer = (
                self.model_cls(**self.attrs)
                if isinstance(self.attrs, dict)
                else self.model_cls(*self.attrs)
            )
785 786 787 788
            model = Model(layer, inputs=self.make_inputs())
            model.prepare()
            if self.param_states:
                model.load(self.param_states, optim_state=None)
789
            return model.predict_batch(self.inputs)
790 791 792 793 794 795

    def check_output_with_place(self, place, mode="test"):
        dygraph_output = self._calc_output(place, mode, dygraph=True)
        stgraph_output = self._calc_output(place, mode, dygraph=False)
        expect_output = getattr(self, "outputs", None)
        for actual_t, expect_t in zip(dygraph_output, stgraph_output):
796
            np.testing.assert_allclose(actual_t, expect_t, rtol=1e-05, atol=0)
797 798
        if expect_output:
            for actual_t, expect_t in zip(dygraph_output, expect_output):
799 800 801
                np.testing.assert_allclose(
                    actual_t, expect_t, rtol=1e-05, atol=0
                )
802 803 804 805 806 807 808 809 810 811 812 813 814 815

    def check_output(self):
        devices = ["CPU", "GPU"] if fluid.is_compiled_with_cuda() else ["CPU"]
        for device in devices:
            place = set_device(device)
            self.check_output_with_place(place)


class TestBeamSearch(ModuleApiTest):
    def setUp(self):
        paddle.set_default_dtype("float64")
        shape = (8, 32)
        self.inputs = [
            np.random.random(shape).astype("float64"),
816
            np.random.random(shape).astype("float64"),
817 818 819 820 821 822 823 824 825 826
        ]
        self.outputs = None
        self.attrs = {
            "vocab_size": 100,
            "embed_dim": 32,
            "hidden_size": 32,
        }
        self.param_states = {}

    @staticmethod
827 828 829 830 831 832 833 834 835 836 837 838 839
    def model_init(
        self,
        vocab_size,
        embed_dim,
        hidden_size,
        bos_id=0,
        eos_id=1,
        beam_size=4,
        max_step_num=20,
    ):
        embedder = paddle.fluid.dygraph.Embedding(
            size=[vocab_size, embed_dim], dtype="float64"
        )
840 841 842
        output_layer = nn.Linear(hidden_size, vocab_size)
        cell = nn.LSTMCell(embed_dim, hidden_size)
        self.max_step_num = max_step_num
843 844 845 846 847 848 849 850
        self.beam_search_decoder = BeamSearchDecoder(
            cell,
            start_token=bos_id,
            end_token=eos_id,
            beam_size=beam_size,
            embedding_fn=embedder,
            output_fn=output_layer,
        )
851 852 853

    @staticmethod
    def model_forward(model, init_hidden, init_cell):
854 855 856 857 858 859 860
        return dynamic_decode(
            model.beam_search_decoder,
            [init_hidden, init_cell],
            max_step_num=model.max_step_num,
            impute_finished=True,
            is_test=True,
        )[0]
861 862 863 864 865 866 867 868

    def make_inputs(self):
        inputs = [
            Input([None, self.inputs[0].shape[-1]], "float64", "init_hidden"),
            Input([None, self.inputs[1].shape[-1]], "float64", "init_cell"),
        ]
        return inputs

869 870 871
    def func_check_output(self):
        self.setUp()
        self.make_inputs()
872 873
        self.check_output()

874 875 876 877 878
    def test_check_output(self):
        with _test_eager_guard():
            self.func_check_output()
        self.func_check_output()

879

G
Guo Sheng 已提交
880 881
if __name__ == '__main__':
    unittest.main()