test_gru_unit_op.py 4.1 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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.
G
guosheng 已提交
14 15 16 17 18 19
import math
import unittest
import numpy as np
from op_test import OpTest


20 21 22 23 24 25 26 27 28 29 30 31
class GRUActivationType(OpTest):
    identity = 0
    sigmoid = 1
    tanh = 2
    relu = 3


def identity(x):
    return x


def sigmoid(x):
G
guosheng 已提交
32 33 34
    return 1. / (1. + np.exp(-x))


35 36 37 38 39 40
def tanh(x):
    return 2. * sigmoid(2. * x) - 1.


def relu(x):
    return np.maximum(x, 0)
G
guosheng 已提交
41 42 43


class TestGRUUnitOp(OpTest):
44 45
    batch_size = 5
    frame_size = 10
46 47 48 49 50 51 52
    activate = {
        GRUActivationType.identity: identity,
        GRUActivationType.sigmoid: sigmoid,
        GRUActivationType.tanh: tanh,
        GRUActivationType.relu: relu,
    }

G
guosheng 已提交
53 54 55
    def set_inputs(self):
        batch_size = self.batch_size
        frame_size = self.frame_size
56
        self.op_type = 'gru_unit'
G
guosheng 已提交
57
        self.inputs = {
58
            'Input': np.random.uniform(
Y
Yu Yang 已提交
59
                -0.1, 0.1, (batch_size, frame_size * 3)).astype('float64'),
60
            'HiddenPrev': np.random.uniform(
Y
Yu Yang 已提交
61
                -0.1, 0.1, (batch_size, frame_size)).astype('float64'),
62
            'Weight': np.random.uniform(
G
guosheng 已提交
63
                -1. / math.sqrt(frame_size), 1. / math.sqrt(frame_size),
Y
Yu Yang 已提交
64
                (frame_size, frame_size * 3)).astype('float64'),
G
guosheng 已提交
65
        }
66 67 68 69
        self.attrs = {
            'activation': GRUActivationType.tanh,
            'gate_activation': GRUActivationType.sigmoid
        }
G
guosheng 已提交
70 71

    def set_outputs(self):
72
        # GRU calculations
G
guosheng 已提交
73 74
        batch_size = self.batch_size
        frame_size = self.frame_size
75 76 77
        x = self.inputs['Input']
        h_p = self.inputs['HiddenPrev']
        w = self.inputs['Weight']
G
guosheng 已提交
78 79
        b = self.inputs['Bias'] if self.inputs.has_key('Bias') else np.zeros(
            (1, frame_size * 3))
G
guosheng 已提交
80 81 82
        g = x + np.tile(b, (batch_size, 1))
        w_u_r = w.flatten()[:frame_size * frame_size * 2].reshape(
            (frame_size, frame_size * 2))
83 84
        u_r = self.activate[self.attrs['gate_activation']](np.dot(
            h_p, w_u_r) + g[:, :frame_size * 2])
G
guosheng 已提交
85 86 87 88 89
        u = u_r[:, :frame_size]
        r = u_r[:, frame_size:frame_size * 2]
        r_h_p = r * h_p
        w_c = w.flatten()[frame_size * frame_size * 2:].reshape(
            (frame_size, frame_size))
90 91
        c = self.activate[self.attrs['activation']](np.dot(r_h_p, w_c) +
                                                    g[:, frame_size * 2:])
G
guosheng 已提交
92
        g = np.hstack((u_r, c))
G
guosheng 已提交
93
        h = u * c + (1 - u) * h_p
Y
Yu Yang 已提交
94 95 96 97 98
        self.outputs = {
            'Gate': g.astype('float64'),
            'ResetHiddenPrev': r_h_p.astype('float64'),
            'Hidden': h.astype('float64')
        }
G
guosheng 已提交
99

G
guosheng 已提交
100 101 102 103
    def setUp(self):
        self.set_inputs()
        self.set_outputs()

G
guosheng 已提交
104 105 106
    def test_check_output(self):
        self.check_output()

G
guosheng 已提交
107
    def test_check_grad(self):
108
        self.check_grad(['Input', 'HiddenPrev', 'Weight'], ['Hidden'])
G
guosheng 已提交
109 110 111 112 113 114 115 116


class TestGRUUnitOpWithBias(TestGRUUnitOp):
    def set_inputs(self):
        batch_size = self.batch_size
        frame_size = self.frame_size
        super(TestGRUUnitOpWithBias, self).set_inputs()
        self.inputs['Bias'] = np.random.uniform(
G
guosheng 已提交
117
            -0.1, 0.1, (1, frame_size * 3)).astype('float64')
G
guosheng 已提交
118 119 120 121 122
        self.attrs = {
            'activation': GRUActivationType.identity,
            'gate_activation': GRUActivationType.sigmoid
        }

G
guosheng 已提交
123
    def test_check_grad(self):
124 125 126
        self.check_grad(['Input', 'HiddenPrev', 'Weight', 'Bias'], ['Hidden'])

    def test_check_grad_ingore_input(self):
G
guosheng 已提交
127
        self.check_grad(
128 129
            ['HiddenPrev', 'Weight', 'Bias'], ['Hidden'],
            no_grad_set=set('Input'))
G
guosheng 已提交
130 131 132 133


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