test_gru_rnn_op.py 5.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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.

15 16
import random
import sys
17 18
import unittest

19
import numpy as np
20
from op_test import OpTest
21

22 23
import paddle
import paddle.fluid.core as core
24

25 26
sys.path.append("./rnn")
from convert import get_params_for_net
27
from rnn_numpy import GRU
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
random.seed(2)
np.set_printoptions(threshold=np.inf)
paddle.enable_static()


class TestGRUOp(OpTest):
    def get_weight_names(self):
        weight_names = []
        for i in range(self.num_layers):
            for j in range(0, 2 * self.direction_num):
                weight_names.append("{}.weight_{}".format(i, j))
        for i in range(self.num_layers):
            for j in range(0, 2 * self.direction_num):
                weight_names.append("{}.bias_{}".format(i, j))
        return weight_names

    def setUp(self):
        self.op_type = "rnn"
R
ronnywang 已提交
47
        self.dtype = "float32" if core.is_compiled_with_rocm() else "float64"
48 49 50 51 52
        self.sequence_length = (
            None
            if core.is_compiled_with_rocm()
            else np.array([12, 11, 10, 9, 8, 7, 6, 5], dtype=np.int32)
        )
53 54 55 56
        self.num_layers = 1
        self.is_bidirec = False
        self.is_test = False
        self.mode = "GRU"
57
        self.dropout = 0.0
58 59 60 61 62 63 64 65 66
        seq_length = 12
        batch_size = 8
        input_size = 4
        self.hidden_size = 2
        self.set_attrs()

        self.direction_num = 2 if self.is_bidirec else 1
        direction = "bidirectional" if self.is_bidirec else "forward"

67 68 69
        input = np.random.uniform(
            low=-0.1, high=0.1, size=(seq_length, batch_size, input_size)
        ).astype(self.dtype)
70 71 72 73 74 75 76

        if self.sequence_length is not None:
            input[3][1:][:] = 0
            input[4][2:][:] = 0
            input[2][3:][:] = 0
            input[1][4:][:] = 0

77 78 79 80 81 82 83 84 85
        rnn1 = GRU(
            input_size,
            self.hidden_size,
            num_layers=self.num_layers,
            time_major=True,
            direction=direction,
            dropout=self.dropout,
            dtype=self.dtype,
        )
86 87 88 89 90

        flat_w = get_params_for_net(rnn1)

        output, last_hidden = rnn1(input, sequence_length=self.sequence_length)

R
ronnywang 已提交
91 92 93 94 95 96 97 98
        if core.is_compiled_with_rocm():

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

            self._get_places = rocm_rnn_get_place

99 100 101
        init_h = np.zeros(
            (self.num_layers * self.direction_num, batch_size, self.hidden_size)
        ).astype(self.dtype)
102 103 104 105 106 107 108

        state_out = np.ndarray((300)).astype("uint8")

        self.inputs = {
            'Input': input,
            'WeightList': flat_w,
            'PreState': [('init_h', init_h)],
109
            'SequenceLength': self.sequence_length,
110 111 112 113 114 115 116 117 118 119 120 121 122 123
        }
        if self.sequence_length is None:
            self.inputs = {
                'Input': input,
                'WeightList': flat_w,
                'PreState': [('init_h', init_h)],
            }
        self.attrs = {
            'dropout_prob': self.dropout,
            'is_bidirec': self.is_bidirec,
            'input_size': input_size,
            'hidden_size': self.hidden_size,
            'num_layers': self.num_layers,
            'is_test': self.is_test,
124
            'mode': self.mode,
125 126 127 128 129
        }
        self.outputs = {
            'Out': output,
            'State': [('last_hidden', last_hidden)],
            'Reserve': np.ndarray((400)).astype("uint8"),
130
            'DropoutState': state_out,
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        }

    def set_attrs(self):
        pass

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

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


class TestGRUOp1(TestGRUOp):
    def set_attrs(self):
        self.sequence_length = None


class TestGRUOp2(TestGRUOp):
    def set_attrs(self):
        self.sequence_length = None
        self.is_bidirec = True


class TestGRUOp3(TestGRUOp):
    def set_attrs(self):
        self.sequence_length = None
        self.is_test = True


class TestGRUOp4(TestGRUOp):
    def set_attrs(self):
        self.sequence_length = None
        self.is_bidirec = True
        self.is_test = True


class TestGRUOpAvx(TestGRUOp):
    def set_attrs(self):
        self.dtype = "float32"
        self.hidden_size = 8


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