test_rnn_op.py 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2018 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 random
import sys
17
import unittest
18

19
import numpy as np
W
wanghuancoder 已提交
20
from eager_op_test import OpTest
21

22
import paddle
23
from paddle.fluid import core
24

L
liulinduo 已提交
25
sys.path.append("../../../../../test/rnn")
26
from convert import get_params_for_net
27
from rnn_numpy import LSTM
28 29 30 31 32 33

random.seed(2)
np.set_printoptions(threshold=np.inf)
paddle.enable_static()


W
wanghuancoder 已提交
34
def rnn_wrapper(
W
wanghuancoder 已提交
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
    Input,
    PreState,
    WeightList=None,
    SequenceLength=None,
    dropout_prob=0.0,
    is_bidirec=False,
    input_size=10,
    hidden_size=100,
    num_layers=1,
    mode="LSTM",
    seed=0,
    is_test=False,
):
    dropout_state_in = paddle.Tensor()
    return paddle._C_ops.rnn(
        Input,
        PreState,
        WeightList,
        SequenceLength,
        dropout_state_in,
        dropout_prob,
        is_bidirec,
        input_size,
        hidden_size,
        num_layers,
        mode,
        seed,
        is_test,
    )


66 67 68 69 70
class TestRNNOp(OpTest):
    def get_weight_names(self):
        weight_names = []
        for i in range(self.num_layers):
            for j in range(0, 2 * self.direction_num):
71
                weight_names.append(f"{i}.weight_{j}")
72 73
        for i in range(self.num_layers):
            for j in range(0, 2 * self.direction_num):
74
                weight_names.append(f"{i}.bias_{j}")
75 76 77 78
        return weight_names

    def setUp(self):
        self.op_type = "rnn"
W
wanghuancoder 已提交
79
        self.python_api = rnn_wrapper
W
wanghuancoder 已提交
80 81
        self.python_out_sig = ["Out", "DropoutState", "State"]
        self.python_out_sig_sub_name = {"State": ["last_hidden", "last_cell"]}
82
        self.dtype = np.float32 if core.is_compiled_with_rocm() else np.float64
83 84 85 86 87
        self.sequence_length = (
            None
            if core.is_compiled_with_rocm()
            else np.array([12, 11, 10, 9, 8], dtype=np.int32)
        )
88 89 90 91 92 93 94 95 96 97 98 99 100 101
        self.num_layers = 1
        self.is_bidirec = False
        self.mode = "LSTM"
        self.is_test = False
        self.dropout = 0.0
        self.set_attrs()

        self.direction_num = 2 if self.is_bidirec else 1
        direction = "bidirectional" if self.is_bidirec else "forward"
        seq_length = 12
        batch_size = 5
        input_size = 3
        hidden_size = 2

102 103 104
        input = np.random.uniform(
            low=-0.1, high=0.1, size=(seq_length, batch_size, input_size)
        ).astype(self.dtype)
105 106 107 108 109 110
        if self.sequence_length is not None:
            input[11][1:][:] = 0
            input[10][2:][:] = 0
            input[9][3:][:] = 0
            input[8][4:][:] = 0

111 112 113 114 115 116 117 118 119
        rnn1 = LSTM(
            input_size,
            hidden_size,
            num_layers=self.num_layers,
            time_major=True,
            direction=direction,
            dropout=self.dropout,
            dtype=self.dtype,
        )
120 121

        flat_w = get_params_for_net(rnn1)
122 123 124
        output, (last_hidden, last_cell) = rnn1(
            input, sequence_length=self.sequence_length
        )
125 126 127 128 129 130 131 132 133

        if core.is_compiled_with_rocm():

            def rocm_rnn_get_place():
                places = [core.CUDAPlace(0)]
                return places

            self._get_places = rocm_rnn_get_place

134 135 136 137 138 139
        init_h = np.zeros(
            (self.num_layers * self.direction_num, batch_size, hidden_size)
        ).astype(self.dtype)
        init_c = np.zeros(
            (self.num_layers * self.direction_num, batch_size, hidden_size)
        ).astype(self.dtype)
140
        state_out = np.ndarray(300).astype("uint8")
141 142 143 144 145

        self.inputs = {
            'Input': input,
            'WeightList': flat_w,
            'PreState': [('init_h', init_h), ('init_c', init_c)],
146
            'SequenceLength': self.sequence_length,
147 148 149 150 151 152 153 154 155 156 157 158 159 160
        }
        if self.sequence_length is None:
            self.inputs = {
                'Input': input,
                'WeightList': flat_w,
                'PreState': [('init_h', init_h), ('init_c', init_c)],
            }
        self.attrs = {
            'dropout_prob': self.dropout,
            'is_bidirec': self.is_bidirec,
            'input_size': input_size,
            'hidden_size': hidden_size,
            'num_layers': self.num_layers,
            'mode': self.mode,
161
            'is_test': self.is_test,
162 163 164 165
        }
        self.outputs = {
            'Out': output,
            "State": [('last_hidden', last_hidden), ('last_cell', last_cell)],
166
            'Reserve': np.ndarray(400).astype("uint8"),
167
            'DropoutState': state_out,
168 169 170 171 172 173 174 175 176 177 178 179 180
        }

    def test_output(self):
        self.check_output(no_check_set=['Reserve', 'DropoutState'])

    def set_attrs(self):
        pass

    def test_grad(self):
        if not self.is_test:
            var_name_list = self.get_weight_names()
            grad_check_list = ['Input', 'init_h', 'init_c']
            grad_check_list.extend(var_name_list)
181 182 183
            self.check_grad(
                set(grad_check_list), ['Out', 'last_hidden', 'last_cell']
            )
184

Y
YuanRisheng 已提交
185 186 187 188 189
    def test_grad_only_input(self):
        if not self.is_test:
            var_name_list = self.get_weight_names()
            grad_check_list = ['Input']
            grad_check_list.extend(var_name_list)
190 191 192
            self.check_grad(
                set(grad_check_list), ['Out', 'last_hidden', 'last_cell']
            )
Y
YuanRisheng 已提交
193 194 195 196 197 198

    def test_grad_only_h(self):
        if not self.is_test:
            var_name_list = self.get_weight_names()
            grad_check_list = ['init_h']
            grad_check_list.extend(var_name_list)
199 200 201
            self.check_grad(
                set(grad_check_list), ['Out', 'last_hidden', 'last_cell']
            )
Y
YuanRisheng 已提交
202 203 204 205 206 207

    def test_grad_only_c(self):
        if not self.is_test:
            var_name_list = self.get_weight_names()
            grad_check_list = ['init_c']
            grad_check_list.extend(var_name_list)
208 209 210
            self.check_grad(
                set(grad_check_list), ['Out', 'last_hidden', 'last_cell']
            )
Y
YuanRisheng 已提交
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

class TestRNNOp1(TestRNNOp):
    def set_attrs(self):
        self.sequence_length = None


class TestRNNOp2(TestRNNOp):
    def set_attrs(self):
        self.sequence_length = None
        self.is_bidirec = True


class TestRNNOp3(TestRNNOp):
    def set_attrs(self):
        self.is_test = True
        self.sequence_length = None


class TestRNNOp4(TestRNNOp):
    def set_attrs(self):
        self.is_test = True
        self.sequence_length = None
        self.is_bidirec = True


class TestRNNOp5(TestRNNOp):
    def set_attrs(self):
        self.num_layers = 2


class TestRNNOp6(TestRNNOp):
    def set_attrs(self):
        self.num_layers = 2
        self.is_bidirec = True


class TestRNNOp7(TestRNNOp):
    def set_attrs(self):
        self.num_layers = 2
        self.is_bidirec = True
        self.is_test = True


class TestRNNOp8(TestRNNOp):
    def set_attrs(self):
        self.num_layers = 2
        self.is_bidirec = True
        self.sequence_length = None


class TestRNNOp9(TestRNNOp):
    def set_attrs(self):
        self.num_layers = 3


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