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

G
Guo Sheng 已提交
17
import numpy
18
import numpy as np
19 20
from rnn.rnn_numpy import LSTMCell
from rnn.rnn_numpy import rnn as numpy_rnn
G
Guo Sheng 已提交
21

22
import paddle
G
Guo Sheng 已提交
23 24
import paddle.fluid as fluid
import paddle.fluid.core as core
25
import paddle.fluid.layers.utils as utils
26
from paddle.fluid import framework
G
Guo Sheng 已提交
27
from paddle.fluid.executor import Executor
28
from paddle.fluid.framework import Program, program_guard
29
from paddle.nn.layer.rnn import rnn as dynamic_rnn
G
Guo Sheng 已提交
30

31
paddle.enable_static()
G
Guo Sheng 已提交
32 33


X
Xing Wu 已提交
34 35 36 37 38 39 40
class TestRnnError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            batch_size = 4
            input_size = 16
            hidden_size = 16
            seq_len = 4
41 42 43
            inputs = fluid.data(
                name='inputs', shape=[None, input_size], dtype='float32'
            )
G
GGBond8488 已提交
44
            pre_hidden = paddle.static.data(
45 46 47 48 49 50 51 52 53 54 55 56 57
                name='pre_hidden',
                shape=[None, hidden_size],
                dtype='float32',
            )
            inputs_basic_lstm = fluid.data(
                name='inputs_basic_lstm',
                shape=[None, None, input_size],
                dtype='float32',
            )
            sequence_length = fluid.data(
                name="sequence_length", shape=[None], dtype='int64'
            )

58
            inputs_dynamic_rnn = paddle.transpose(
59 60
                inputs_basic_lstm, perm=[1, 0, 2]
            )
61 62 63
            cell = paddle.nn.LSTMCell(
                input_size, hidden_size, name="LSTMCell_for_rnn"
            )
X
Xing Wu 已提交
64
            np_inputs_dynamic_rnn = np.random.random(
65 66
                (seq_len, batch_size, input_size)
            ).astype("float32")
X
Xing Wu 已提交
67 68

            def test_input_Variable():
69 70 71 72 73 74
                dynamic_rnn(
                    cell=cell,
                    inputs=np_inputs_dynamic_rnn,
                    sequence_length=sequence_length,
                    is_reverse=False,
                )
X
Xing Wu 已提交
75 76 77 78

            self.assertRaises(TypeError, test_input_Variable)

            def test_input_list():
79 80 81 82 83 84
                dynamic_rnn(
                    cell=cell,
                    inputs=[np_inputs_dynamic_rnn],
                    sequence_length=sequence_length,
                    is_reverse=False,
                )
X
Xing Wu 已提交
85 86 87 88

            self.assertRaises(TypeError, test_input_list)

            def test_initial_states_type():
89 90 91
                cell = paddle.nn.GRUCell(
                    input_size, hidden_size, name="GRUCell_for_rnn"
                )
X
Xing Wu 已提交
92
                error_initial_states = np.random.random(
93 94 95 96 97 98 99 100 101
                    (batch_size, hidden_size)
                ).astype("float32")
                dynamic_rnn(
                    cell=cell,
                    inputs=inputs_dynamic_rnn,
                    initial_states=error_initial_states,
                    sequence_length=sequence_length,
                    is_reverse=False,
                )
X
Xing Wu 已提交
102 103 104 105 106

            self.assertRaises(TypeError, test_initial_states_type)

            def test_initial_states_list():
                error_initial_states = [
107 108 109 110 111 112
                    np.random.random((batch_size, hidden_size)).astype(
                        "float32"
                    ),
                    np.random.random((batch_size, hidden_size)).astype(
                        "float32"
                    ),
X
Xing Wu 已提交
113
                ]
114 115 116 117 118 119 120
                dynamic_rnn(
                    cell=cell,
                    inputs=inputs_dynamic_rnn,
                    initial_states=error_initial_states,
                    sequence_length=sequence_length,
                    is_reverse=False,
                )
X
Xing Wu 已提交
121 122 123 124

            self.assertRaises(TypeError, test_initial_states_type)

            def test_sequence_length_type():
125 126 127 128 129 130 131 132 133
                np_sequence_length = np.random.random((batch_size)).astype(
                    "float32"
                )
                dynamic_rnn(
                    cell=cell,
                    inputs=inputs_dynamic_rnn,
                    sequence_length=np_sequence_length,
                    is_reverse=False,
                )
X
Xing Wu 已提交
134 135 136 137

            self.assertRaises(TypeError, test_sequence_length_type)


G
Guo Sheng 已提交
138 139 140 141 142 143 144 145 146
class TestRnn(unittest.TestCase):
    def setUp(self):
        self.batch_size = 4
        self.input_size = 16
        self.hidden_size = 16
        self.seq_len = 4

    def test_run(self):

147 148
        numpy_cell = LSTMCell(self.input_size, self.hidden_size)
        dynamic_cell = paddle.nn.LSTMCell(self.input_size, self.hidden_size)
G
Guo Sheng 已提交
149 150 151 152 153 154 155 156

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
        exe = Executor(place)
        exe.run(framework.default_startup_program())

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        state = numpy_cell.parameters
        for k, v in dynamic_cell.named_parameters():
            param = np.random.uniform(-0.1, 0.1, size=state[k].shape).astype(
                'float64'
            )
            setattr(numpy_cell, k, param)
            fluid.global_scope().find_var(v.name).get_tensor().set(param, place)

        sequence_length = fluid.data(
            name="sequence_length", shape=[None], dtype='int64'
        )
        inputs_rnn = fluid.data(
            name='inputs_rnn',
            shape=[None, None, self.input_size],
            dtype='float64',
        )
        pre_hidden = fluid.data(
            name='pre_hidden', shape=[None, self.hidden_size], dtype='float64'
        )
        pre_cell = fluid.data(
            name='pre_cell', shape=[None, self.hidden_size], dtype='float64'
        )

        dynamic_output, dynamic_final_state = dynamic_rnn(
            cell=dynamic_cell,
            inputs=inputs_rnn,
            sequence_length=sequence_length,
            initial_states=(pre_hidden, pre_cell),
            is_reverse=False,
        )

        inputs_rnn_np = np.random.uniform(
            -0.1, 0.1, (self.batch_size, self.seq_len, self.input_size)
        ).astype('float64')
191 192 193
        sequence_length_np = (
            np.ones(self.batch_size, dtype='int64') * self.seq_len
        )
G
Guo Sheng 已提交
194
        pre_hidden_np = np.random.uniform(
195
            -0.1, 0.1, (self.batch_size, self.hidden_size)
196
        ).astype('float64')
G
Guo Sheng 已提交
197
        pre_cell_np = np.random.uniform(
198
            -0.1, 0.1, (self.batch_size, self.hidden_size)
199
        ).astype('float64')
200

201 202 203 204 205 206 207 208 209
        o1, _ = numpy_rnn(
            cell=numpy_cell,
            inputs=inputs_rnn_np,
            initial_states=(pre_hidden_np, pre_cell_np),
            sequence_length=sequence_length_np,
            is_reverse=False,
        )

        o2 = exe.run(
210
            feed={
211
                'inputs_rnn': inputs_rnn_np,
212 213 214 215
                'sequence_length': sequence_length_np,
                'pre_hidden': pre_hidden_np,
                'pre_cell': pre_cell_np,
            },
216 217 218
            fetch_list=[dynamic_output],
        )[0]
        np.testing.assert_allclose(o1, o2, rtol=0.001)
G
Guo Sheng 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239


class TestRnnUtil(unittest.TestCase):
    """
    Test cases for rnn apis' utility methods for coverage.
    """

    def test_case(self):
        inputs = {"key1": 1, "key2": 2}
        func = lambda x: x + 1
        outputs = utils.map_structure(func, inputs)
        utils.assert_same_structure(inputs, outputs)
        try:
            inputs["key3"] = 3
            utils.assert_same_structure(inputs, outputs)
        except ValueError as identifier:
            pass


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