test_basic_lstm_unit_op.py 4.4 KB
Newer Older
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

17
import numpy
18 19
import numpy as np

20 21
import paddle.fluid as fluid
import paddle.fluid.core as core
22 23
import paddle.fluid.layers as layers
from paddle.fluid import framework
24 25 26
from paddle.fluid.contrib.layers import BasicLSTMUnit
from paddle.fluid.executor import Executor

27 28
np.set_seed(123)

29 30 31 32 33 34 35 36 37
SIGMOID_THRESHOLD_MIN = -40.0
SIGMOID_THRESHOLD_MAX = 13.0
EXP_MAX_INPUT = 40.0


def sigmoid(x):
    y = np.copy(x)
    y[x < SIGMOID_THRESHOLD_MIN] = SIGMOID_THRESHOLD_MIN
    y[x > SIGMOID_THRESHOLD_MAX] = SIGMOID_THRESHOLD_MAX
38
    return 1.0 / (1.0 + np.exp(-y))
39 40 41


def tanh(x):
42
    y = -2.0 * x
43
    y[y > EXP_MAX_INPUT] = EXP_MAX_INPUT
44
    return (2.0 / (1.0 + np.exp(y))) - 1.0
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66


def step(step_in, pre_hidden, pre_cell, gate_w, gate_b, forget_bias=1.0):
    concat_1 = np.concatenate([step_in, pre_hidden], 1)

    gate_input = np.matmul(concat_1, gate_w)
    gate_input += gate_b
    i, j, f, o = np.split(gate_input, indices_or_sections=4, axis=1)

    new_cell = pre_cell * sigmoid(f + forget_bias) + sigmoid(i) * tanh(j)
    new_hidden = tanh(new_cell) * sigmoid(o)

    return new_hidden, new_cell


class TestBasicGRUUnit(unittest.TestCase):
    def setUp(self):
        self.hidden_size = 5
        self.batch_size = 5

    def test_run(self):
        x = layers.data(name='x', shape=[-1, self.hidden_size], dtype='float32')
67 68 69 70 71 72
        pre_hidden = layers.data(
            name="pre_hidden", shape=[-1, self.hidden_size], dtype='float32'
        )
        pre_cell = layers.data(
            name="pre_cell", shape=[-1, self.hidden_size], dtype='float32'
        )
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

        lstm_unit = BasicLSTMUnit("lstm_unit", self.hidden_size)

        new_hidden, new_cell = lstm_unit(x, pre_hidden, pre_cell)

        new_hidden.persisbale = True
        new_cell.persisbale = True

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

        exe = Executor(place)
        exe.run(framework.default_startup_program())

        param_list = fluid.default_main_program().block(0).all_parameters()

        # process weight and bias

        gate_w_name = "lstm_unit/BasicLSTMUnit_0.w_0"
        gate_b_name = "lstm_unit/BasicLSTMUnit_0.b_0"

96
        gate_w = np.array(
97 98 99 100 101
            fluid.global_scope().find_var(gate_w_name).get_tensor()
        )
        gate_w = np.random.uniform(-0.1, 0.1, size=gate_w.shape).astype(
            'float32'
        )
102
        fluid.global_scope().find_var(gate_w_name).get_tensor().set(
103 104
            gate_w, place
        )
105 106

        gate_b = np.array(
107 108 109 110 111
            fluid.global_scope().find_var(gate_b_name).get_tensor()
        )
        gate_b = np.random.uniform(-0.1, 0.1, size=gate_b.shape).astype(
            'float32'
        )
112
        fluid.global_scope().find_var(gate_b_name).get_tensor().set(
113 114
            gate_b, place
        )
115 116

        step_input_np = np.random.uniform(
117 118
            -0.1, 0.1, (self.batch_size, self.hidden_size)
        ).astype('float32')
119
        pre_hidden_np = np.random.uniform(
120 121
            -0.1, 0.1, (self.batch_size, self.hidden_size)
        ).astype('float32')
122
        pre_cell_np = np.random.uniform(
123 124 125 126 127 128 129 130 131 132 133
            -0.1, 0.1, (self.batch_size, self.hidden_size)
        ).astype('float32')

        out = exe.run(
            feed={
                'x': step_input_np,
                'pre_hidden': pre_hidden_np,
                'pre_cell': pre_cell_np,
            },
            fetch_list=[new_hidden, new_cell],
        )
134 135 136 137

        api_hidden_out = out[0]
        api_cell_out = out[1]

138 139 140 141 142 143 144 145 146 147
        np_hidden_out, np_cell_out = step(
            step_input_np, pre_hidden_np, pre_cell_np, gate_w, gate_b
        )

        np.testing.assert_allclose(
            api_hidden_out, np_hidden_out, rtol=0.0001, atol=0
        )
        np.testing.assert_allclose(
            api_cell_out, np_cell_out, rtol=0.0001, atol=0
        )
148 149 150 151


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