test_lstm_op.py 9.9 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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
from __future__ import print_function

17 18
import unittest
import numpy as np
19
from op_test import OpTest
20

21 22 23 24
SIGMOID_THRESHOLD_MIN = -40.0
SIGMOID_THRESHOLD_MAX = 13.0
EXP_MAX_INPUT = 40.0

25 26 27 28 29 30

def identity(x):
    return x


def sigmoid(x):
31 32 33 34
    y = np.copy(x)
    y[x < SIGMOID_THRESHOLD_MIN] = SIGMOID_THRESHOLD_MIN
    y[x > SIGMOID_THRESHOLD_MAX] = SIGMOID_THRESHOLD_MAX
    return 1. / (1. + np.exp(-y))
35 36 37


def tanh(x):
38 39 40
    y = -2. * x
    y[y > EXP_MAX_INPUT] = EXP_MAX_INPUT
    return (2. / (1. + np.exp(y))) - 1.
41 42 43 44 45 46


def relu(x):
    return np.maximum(x, 0)


47
ACTIVATION = {
D
dangqingqing 已提交
48 49 50 51 52 53 54
    'identity': identity,
    'sigmoid': sigmoid,
    'tanh': tanh,
    'relu': relu
}


55 56 57 58 59 60 61 62 63
def lstm(
        input,  # T x 4D
        lod,  # 1 x N
        h0=None,  # N x D
        c0=None,  # N x D
        w_h=None,  # D x 4D
        w_b=None,  # 1 x 4D
        w_c=None,  # 1 x 3D
        is_reverse=False,
D
dangqingqing 已提交
64 65 66 67
        act_gate=None,
        act_cell=None,
        act_cand=None):
    def _step(x, w_h, w_c, h_pre, c_pre, act_gate, act_cell, act_cand):
68 69 70
        g = np.dot(h_pre, w_h)  # 1 x 4D
        g = g + x
        g = np.reshape(g, (1, g.size))
D
dangqingqing 已提交
71
        c, g_i, g_f, g_o = np.split(g, 4, axis=1)
72
        if w_c is None:
D
dangqingqing 已提交
73 74
            g_i = act_gate(g_i)  # 1 x D
            g_f = act_gate(g_f)  # 1 x D
75 76
        else:
            w_ic, w_fc, w_oc = np.split(w_c, 3, axis=1)
D
dangqingqing 已提交
77 78
            g_i = act_gate(g_i + w_ic * c_pre)  # 1 x D
            g_f = act_gate(g_f + w_fc * c_pre)  # 1 x D
D
dangqingqing 已提交
79
        c = g_f * c_pre + g_i * act_cand(c)  # 1 x D
80 81

        if w_c is None:
D
dangqingqing 已提交
82
            g_o = act_gate(g_o)  # 1 x D
83 84
        else:
            _, _, w_oc = np.split(w_c, 3, axis=1)
D
dangqingqing 已提交
85 86
            g_o = act_gate(g_o + w_oc * c)  # 1 x D
        h = g_o * act_cell(c)
D
dangqingqing 已提交
87
        return h, c
88

89
    def _reverse(x, offset):
D
dangqingqing 已提交
90
        y = np.zeros_like(x)
91 92
        for i in range(len(offset) - 1):
            b, e = offset[i], offset[i + 1]
D
dangqingqing 已提交
93 94 95
            y[b:e, :] = np.flip(x[b:e, :], 0)
        return y

96 97 98 99
    offset = [0]
    for l in lod[0]:
        offset.append(offset[-1] + l)
    batch_size = len(lod[0])
100 101
    hidden = []
    cell = []
D
dangqingqing 已提交
102
    input = _reverse(input, offset) if is_reverse else input
103 104 105 106
    if w_b is not None:
        input = input + np.tile(w_b, (offset[-1], 1))
    for i in range(batch_size):
        # compute one sequence
107
        seq_len = lod[0][i]
108 109
        x = input[offset[i]:offset[i + 1], :]
        h_pre = h0[i]  # 1 x D
110
        c_pre = c0[i]  # 1 x D
111 112
        for j in range(seq_len):
            # compute one step
D
dangqingqing 已提交
113 114
            h_pre, c_pre = _step(x[j], w_h, w_c, h_pre, c_pre, act_gate,
                                 act_cell, act_cand)
115 116 117
            hidden.append(h_pre.flatten())
            cell.append(c_pre.flatten())

118 119
    hidden = np.array(hidden).astype('float64')
    cell = np.array(cell).astype('float64')
D
dangqingqing 已提交
120 121 122 123

    hidden = _reverse(hidden, offset) if is_reverse else hidden
    cell = _reverse(cell, offset) if is_reverse else cell

124 125
    assert hidden.shape == (input.shape[0], input.shape[1] / 4)
    assert cell.shape == (input.shape[0], input.shape[1] / 4)
D
dangqingqing 已提交
126
    return hidden, cell
127 128


D
dangqingqing 已提交
129
class TestLstmOp(OpTest):
130
    def set_lod(self):
131
        self.lod = [[2, 3, 2]]
132 133 134

    def set_argument(self):
        self.set_lod()
135 136
        self.D = 16

137 138 139
        self.act_gate = 'sigmoid'
        self.act_cell = 'tanh'
        self.act_cand = 'tanh'
D
dangqingqing 已提交
140

D
dangqingqing 已提交
141
        self.has_initial_state = False
D
dangqingqing 已提交
142
        self.is_reverse = False
D
dangqingqing 已提交
143
        self.use_peepholes = True
D
dangqingqing 已提交
144 145

    def setUp(self):
146
        self.set_argument()
147
        self.op_type = 'lstm'
148 149
        T = sum(self.lod[0])
        N = len(self.lod[0])
D
dangqingqing 已提交
150

151
        x = np.random.normal(size=(T, 4 * self.D)).astype('float64')
D
dangqingqing 已提交
152 153 154 155 156 157
        if self.has_initial_state:
            h0 = np.random.normal(size=(N, self.D)).astype('float64')
            c0 = np.random.normal(size=(N, self.D)).astype('float64')
        else:
            h0 = np.zeros((N, self.D)).astype('float64')
            c0 = np.zeros((N, self.D)).astype('float64')
158
        w = np.random.normal(size=(self.D, 4 * self.D)).astype('float64')
D
dangqingqing 已提交
159 160 161 162
        if self.use_peepholes:
            b = np.random.normal(size=(1, 7 * self.D)).astype('float64')
        else:
            b = np.random.normal(size=(1, 4 * self.D)).astype('float64')
D
dangqingqing 已提交
163

D
dangqingqing 已提交
164 165
        w_b = b[:, 0:4 * self.D]
        w_c = b[:, 4 * self.D:] if self.use_peepholes else None
D
dangqingqing 已提交
166
        h, c = lstm(x, self.lod, h0, c0, w, w_b, w_c, self.is_reverse,
167 168
                    ACTIVATION[self.act_gate], ACTIVATION[self.act_cell],
                    ACTIVATION[self.act_cand])
169

170 171
        self.inputs = {'Input': (x, self.lod), 'Weight': w}

D
dangqingqing 已提交
172
        self.inputs['Bias'] = b
173

D
dangqingqing 已提交
174 175 176
        if self.has_initial_state:
            self.inputs['H0'] = h0
            self.inputs['C0'] = c0
177

178 179 180 181
        self.outputs = {
            'Hidden': (h, self.lod),
            'Cell': (c, self.lod),
        }
182
        self.attrs = {
D
dangqingqing 已提交
183
            'use_peepholes': self.use_peepholes,
184 185 186 187
            'is_reverse': self.is_reverse,
            'gate_activation': self.act_gate,
            'cell_activation': self.act_cell,
            'candidate_activation': self.act_cand
188 189
        }

D
dangqingqing 已提交
190
    def test_check_output(self):
H
hong 已提交
191
        self.check_output(atol=1e-8, check_dygraph=False)
192

D
dangqingqing 已提交
193
    def test_check_grad(self):
D
dangqingqing 已提交
194
        # TODO(qingqing) remove folowing lines after the check_grad is refined.
195
        N = len(self.lod[0])
D
dangqingqing 已提交
196 197 198
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
199
        self.check_grad(
H
hong 已提交
200 201 202
            ['Input', 'Weight', 'Bias'], ['Hidden'],
            max_relative_error=5e-4,
            check_dygraph=False)
203 204


205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
class TestLstmOpCase1(TestLstmOp):
    def set_lod(self):
        self.lod = [[0, 3, 2]]


class TestLstmOpCase2(TestLstmOp):
    def set_lod(self):
        self.lod = [[0, 3, 0]]


class TestLstmOpCase3(TestLstmOp):
    def set_lod(self):
        self.lod = [[2, 0, 4]]


220 221
# class TestLstmOpHasInitial(TestLstmOp):
#     def set_argument(self):
222
#         self.lod = [[2, 3, 2]]
223 224 225 226 227 228 229 230 231 232 233 234
#         self.D = 16

#         self.act_gate = 'sigmoid'
#         self.act_cell = 'tanh'
#         self.act_cand = 'tanh'

#         self.has_initial_state = True
#         self.is_reverse = True
#         self.use_peepholes = True

#     def test_check_grad(self):
#         # TODO(qingqing) remove folowing lines after the check_grad is refined.
235
#         N = len(self.lod[0])
236 237 238 239 240 241 242 243
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Input', 'Weight', 'Bias', 'H0', 'C0'], ['Hidden'],
#             max_relative_error=5e-4)

#     def test_check_grad_ingore_bias(self):
244
#         N = len(self.lod[0])
245 246 247 248 249 250 251 252 253
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Input', 'Weight'], ['Hidden'],
#             max_relative_error=5e-4,
#             no_grad_set=set('Bias'))

#     def test_check_grad_ingore_weight(self):
254
#         N = len(self.lod[0])
255 256 257 258 259 260 261 262 263
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Input', 'Bias'], ['Hidden'],
#             max_relative_error=5e-4,
#             no_grad_set=set('Weight'))

#     def test_check_grad_ingore_input(self):
264
#         N = len(self.lod[0])
265 266 267 268 269 270 271 272 273
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Weight', 'Bias'], ['Hidden'],
#             max_relative_error=5e-4,
#             no_grad_set=set('Input'))

#     def test_check_grad_ingore_h0(self):
274
#         N = len(self.lod[0])
275 276 277 278 279 280 281 282 283
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Input', 'Weight', 'Bias', 'C0'], ['Hidden'],
#             max_relative_error=5e-4,
#             no_grad_set=set('H0'))

#     def test_check_grad_ingore_c0(self):
284
#         N = len(self.lod[0])
285 286 287 288 289 290 291 292 293 294
#         self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
#         self.outputs['BatchCellPreAct'] = np.zeros(
#             (N, self.D)).astype('float64')
#         self.check_grad(
#             ['Input', 'Weight', 'Bias', 'H0'], ['Hidden'],
#             max_relative_error=5e-4,
#             no_grad_set=set('C0'))

# class TestLstmOpRerverse(TestLstmOp):
#     def set_argument(self):
295
#         self.lod = [[2, 3, 2]]
296 297 298 299 300 301 302 303 304 305 306 307
#         self.D = 16

#         self.act_gate = 'sigmoid'
#         self.act_cell = 'tanh'
#         self.act_cand = 'tanh'

#         self.has_initial_state = False
#         self.is_reverse = True
#         self.use_peepholes = True

# class TestLstmOpNotUsePeepholes(TestLstmOp):
#     def set_argument(self):
308
#         self.lod = [[2, 3, 2]]
309 310 311 312 313 314 315 316 317
#         self.D = 16

#         self.act_gate = 'sigmoid'
#         self.act_cell = 'tanh'
#         self.act_cand = 'tanh'

#         self.has_initial_state = False
#         self.is_reverse = True
#         self.use_peepholes = False
318 319

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