test_cudnn_grucell.py 8.4 KB
Newer Older
X
Xing Wu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.

import unittest
import paddle.fluid as fluid
import paddle.fluid.core as core
X
Xing Wu 已提交
18
from paddle.fluid.dygraph import GRUCell
X
Xing Wu 已提交
19 20 21 22 23 24 25

import numpy as np

np.random.seed = 123


def sigmoid(x):
26
    return 1.0 / (1.0 + np.exp(-x))
X
Xing Wu 已提交
27 28 29


def tanh(x):
30
    return 2.0 * sigmoid(2.0 * x) - 1.0
X
Xing Wu 已提交
31 32


33 34 35
def cudnn_step(
    step_input_np, pre_hidden_np, weight_ih, bias_ih, weight_hh, bias_hh
):
36
    igates = np.matmul(step_input_np, weight_ih.transpose(1, 0))
X
Xing Wu 已提交
37
    igates += bias_ih
38
    hgates = np.matmul(pre_hidden_np, weight_hh.transpose(1, 0))
X
Xing Wu 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    hgates += bias_hh

    chunked_igates = np.split(igates, indices_or_sections=3, axis=1)
    chunked_hgates = np.split(hgates, indices_or_sections=3, axis=1)

    reset_gate = chunked_igates[0] + chunked_hgates[0]
    reset_gate = sigmoid(reset_gate)

    input_gate = chunked_igates[1] + chunked_hgates[1]
    input_gate = sigmoid(input_gate)

    _temp = reset_gate * chunked_hgates[2]
    new_gate = chunked_igates[2] + _temp
    new_gate = tanh(new_gate)

    new_hidden = (pre_hidden_np - new_gate) * input_gate + new_gate

    return new_hidden


59 60 61
def non_cudnn_step(
    step_in, pre_hidden, gate_w, gate_b, candidate_w, candidate_b
):
X
Xing Wu 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    concat_1 = np.concatenate([step_in, pre_hidden], 1)

    gate_input = np.matmul(concat_1, gate_w)
    gate_input += gate_b
    gate_input = sigmoid(gate_input)
    r, u = np.split(gate_input, indices_or_sections=2, axis=1)

    r_hidden = r * pre_hidden

    candidate = np.matmul(np.concatenate([step_in, r_hidden], 1), candidate_w)

    candidate += candidate_b
    c = tanh(candidate)

    new_hidden = u * pre_hidden + (1 - u) * c

    return new_hidden


class TestCudnnGRU(unittest.TestCase):
    def setUp(self):
        self.input_size = 100
        self.hidden_size = 200
        self.batch_size = 64

    def test_run(self):

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()

        with fluid.dygraph.guard(place):
            param_attr = fluid.ParamAttr(name="param_attr")
            bias_attr = fluid.ParamAttr(name="bias_attr")
97 98 99
            named_cudnn_gru = GRUCell(
                self.hidden_size, self.input_size, param_attr, bias_attr
            )
X
Xing Wu 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
            cudnn_gru = GRUCell(self.hidden_size, self.input_size)

            param_list = cudnn_gru.state_dict()
            named_param_list = named_cudnn_gru.state_dict()

            # process weight and bias

            weight_ih_name = "_weight_ih"
            bias_ih_name = "_bias_ih"
            weight_hh_name = "_weight_hh"
            bias_hh_name = "_bias_hh"

            weight_ih = param_list[weight_ih_name].numpy()
            weight_ih = np.random.uniform(
114 115
                -0.1, 0.1, size=weight_ih.shape
            ).astype('float64')
X
Xing Wu 已提交
116 117 118 119
            param_list[weight_ih_name].set_value(weight_ih)
            named_param_list[weight_ih_name].set_value(weight_ih)

            bias_ih = param_list[bias_ih_name].numpy()
120 121 122
            bias_ih = np.random.uniform(-0.1, 0.1, size=bias_ih.shape).astype(
                'float64'
            )
X
Xing Wu 已提交
123 124 125 126 127
            param_list[bias_ih_name].set_value(bias_ih)
            named_param_list[bias_ih_name].set_value(bias_ih)

            weight_hh = param_list[weight_hh_name].numpy()
            weight_hh = np.random.uniform(
128 129
                -0.1, 0.1, size=weight_hh.shape
            ).astype('float64')
X
Xing Wu 已提交
130 131 132 133
            param_list[weight_hh_name].set_value(weight_hh)
            named_param_list[weight_hh_name].set_value(weight_hh)

            bias_hh = param_list[bias_hh_name].numpy()
134 135 136
            bias_hh = np.random.uniform(-0.1, 0.1, size=bias_hh.shape).astype(
                'float64'
            )
X
Xing Wu 已提交
137 138 139
            param_list[bias_hh_name].set_value(bias_hh)
            named_param_list[bias_hh_name].set_value(bias_hh)

140
            step_input_np = np.random.uniform(
141 142
                -0.1, 0.1, (self.batch_size, self.input_size)
            ).astype('float64')
143
            pre_hidden_np = np.random.uniform(
144 145
                -0.1, 0.1, (self.batch_size, self.hidden_size)
            ).astype('float64')
X
Xing Wu 已提交
146 147 148 149 150 151

            step_input_var = fluid.dygraph.to_variable(step_input_np)
            pre_hidden_var = fluid.dygraph.to_variable(pre_hidden_np)
            api_out = cudnn_gru(step_input_var, pre_hidden_var)
            named_api_out = named_cudnn_gru(step_input_var, pre_hidden_var)

152 153 154
        np_out = cudnn_step(
            step_input_np, pre_hidden_np, weight_ih, bias_ih, weight_hh, bias_hh
        )
X
Xing Wu 已提交
155

156
        np.testing.assert_allclose(api_out.numpy(), np_out, rtol=1e-05, atol=0)
157 158 159
        np.testing.assert_allclose(
            named_api_out.numpy(), np_out, rtol=1e-05, atol=0
        )
X
Xing Wu 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177


class TestNonCudnnGRU(unittest.TestCase):
    def setUp(self):
        self.input_size = 100
        self.hidden_size = 200
        self.batch_size = 64

    def test_run(self):

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()

        with fluid.dygraph.guard(place):
            param_attr = fluid.ParamAttr(name="param_attr")
            bias_attr = fluid.ParamAttr(name="bias_attr")
178 179 180 181 182 183 184 185 186 187
            named_non_cudnn_gru = GRUCell(
                self.hidden_size,
                self.input_size,
                param_attr,
                bias_attr,
                use_cudnn_impl=False,
            )
            non_cudnn_gru = GRUCell(
                self.hidden_size, self.input_size, use_cudnn_impl=False
            )
X
Xing Wu 已提交
188 189 190 191 192 193 194 195 196 197 198 199

            param_list = non_cudnn_gru.state_dict()
            named_param_list = named_non_cudnn_gru.state_dict()

            # process weight and bias

            gate_w_name = "_gate_weight"
            gate_b_name = "_gate_bias"
            candidate_w_name = "_candidate_weight"
            candidate_b_name = "_candidate_bias"

            gate_w = param_list[gate_w_name].numpy()
200 201 202
            gate_w = np.random.uniform(-0.1, 0.1, size=gate_w.shape).astype(
                'float64'
            )
X
Xing Wu 已提交
203 204 205 206
            param_list[gate_w_name].set_value(gate_w)
            named_param_list[gate_w_name].set_value(gate_w)

            gate_b = param_list[gate_b_name].numpy()
207 208 209
            gate_b = np.random.uniform(-0.1, 0.1, size=gate_b.shape).astype(
                'float64'
            )
X
Xing Wu 已提交
210 211 212 213 214
            param_list[gate_b_name].set_value(gate_b)
            named_param_list[gate_b_name].set_value(gate_b)

            candidate_w = param_list[candidate_w_name].numpy()
            candidate_w = np.random.uniform(
215 216
                -0.1, 0.1, size=candidate_w.shape
            ).astype('float64')
X
Xing Wu 已提交
217 218 219 220 221
            param_list[candidate_w_name].set_value(candidate_w)
            named_param_list[candidate_w_name].set_value(candidate_w)

            candidate_b = param_list[candidate_b_name].numpy()
            candidate_b = np.random.uniform(
222 223
                -0.1, 0.1, size=candidate_b.shape
            ).astype('float64')
X
Xing Wu 已提交
224 225 226
            param_list[candidate_b_name].set_value(candidate_b)
            named_param_list[candidate_b_name].set_value(candidate_b)

227
            step_input_np = np.random.uniform(
228 229
                -0.1, 0.1, (self.batch_size, self.input_size)
            ).astype('float64')
230
            pre_hidden_np = np.random.uniform(
231 232
                -0.1, 0.1, (self.batch_size, self.hidden_size)
            ).astype('float64')
X
Xing Wu 已提交
233 234 235 236 237 238

            step_input_var = fluid.dygraph.to_variable(step_input_np)
            pre_hidden_var = fluid.dygraph.to_variable(pre_hidden_np)
            api_out = non_cudnn_gru(step_input_var, pre_hidden_var)
            named_api_out = named_non_cudnn_gru(step_input_var, pre_hidden_var)

239 240 241 242 243 244 245 246
        np_out = non_cudnn_step(
            step_input_np,
            pre_hidden_np,
            gate_w,
            gate_b,
            candidate_w,
            candidate_b,
        )
X
Xing Wu 已提交
247

248
        np.testing.assert_allclose(api_out.numpy(), np_out, rtol=1e-05, atol=0)
249 250 251
        np.testing.assert_allclose(
            named_api_out.numpy(), np_out, rtol=1e-05, atol=0
        )
X
Xing Wu 已提交
252 253 254 255


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