test_lstm_op.py 14.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, skip_check_grad_ci
X
Xing Wu 已提交
20
from paddle import fluid
J
Jiangxinz 已提交
21 22
from paddle.fluid.layers import lstm as LSTM
from paddle.fluid.layers import fill_constant
X
Xing Wu 已提交
23
from paddle.fluid.framework import program_guard, Program
24

25 26 27 28
SIGMOID_THRESHOLD_MIN = -40.0
SIGMOID_THRESHOLD_MAX = 13.0
EXP_MAX_INPUT = 40.0

29 30 31 32 33 34

def identity(x):
    return x


def sigmoid(x):
35 36 37 38
    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))
39 40 41


def tanh(x):
42 43 44
    y = -2. * x
    y[y > EXP_MAX_INPUT] = EXP_MAX_INPUT
    return (2. / (1. + np.exp(y))) - 1.
45 46 47 48 49 50


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


51
ACTIVATION = {
D
dangqingqing 已提交
52 53 54 55 56 57 58
    'identity': identity,
    'sigmoid': sigmoid,
    'tanh': tanh,
    'relu': relu
}


59 60 61 62 63 64 65 66 67
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 已提交
68 69 70 71
        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):
72 73 74
        g = np.dot(h_pre, w_h)  # 1 x 4D
        g = g + x
        g = np.reshape(g, (1, g.size))
D
dangqingqing 已提交
75
        c, g_i, g_f, g_o = np.split(g, 4, axis=1)
76
        if w_c is None:
D
dangqingqing 已提交
77 78
            g_i = act_gate(g_i)  # 1 x D
            g_f = act_gate(g_f)  # 1 x D
79 80
        else:
            w_ic, w_fc, w_oc = np.split(w_c, 3, axis=1)
D
dangqingqing 已提交
81 82
            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 已提交
83
        c = g_f * c_pre + g_i * act_cand(c)  # 1 x D
84 85

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

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

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

122 123
    hidden = np.array(hidden).astype('float64')
    cell = np.array(cell).astype('float64')
D
dangqingqing 已提交
124 125 126 127

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

128 129
    assert hidden.shape == (input.shape[0], input.shape[1] / 4)
    assert cell.shape == (input.shape[0], input.shape[1] / 4)
D
dangqingqing 已提交
130
    return hidden, cell
131 132


X
Xing Wu 已提交
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
class LstmUnitTestError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            batch_size = 20
            seq_len = 100
            dropout_prob = 0.2
            hidden_size = 150
            num_layers = 1
            input = fluid.data(
                name='input',
                shape=[batch_size, seq_len, hidden_size],
                dtype='float32')
            pre_hidden = fill_constant([num_layers, batch_size, hidden_size],
                                       'float32', 0.0)
            pre_cell = fill_constant([num_layers, batch_size, hidden_size],
                                     'float32', 0.0)

            np_input = np.random.uniform(
                -0.1, 0.1, (batch_size, seq_len, hidden_size)).astype('float64')
            np_pre_hidden = np.random.uniform(
                -0.1, 0.1,
                (num_layers, batch_size, hidden_size)).astype('float64')
            np_pre_cell = np.random.uniform(
                -0.1, 0.1,
                (num_layers, batch_size, hidden_size)).astype('float64')

            def test_input_Variable():
J
Jiangxinz 已提交
160
                LSTM(np_input, pre_hidden, pre_cell, \
X
Xing Wu 已提交
161 162 163 164 165 166
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_input_Variable)

            def test_pre_hidden_Variable():
J
Jiangxinz 已提交
167
                LSTM(np_input, np_pre_hidden, pre_cell, \
X
Xing Wu 已提交
168 169 170 171 172 173
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_pre_hidden_Variable)

            def test_pre_cell_Variable():
J
Jiangxinz 已提交
174
                LSTM(np_input, pre_hidden, np_pre_cell, \
X
Xing Wu 已提交
175 176 177 178 179 180 181 182 183 184
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_pre_cell_Variable)

            def test_input_type():
                error_input = fluid.data(
                    name='error_input',
                    shape=[None, hidden_size * 3],
                    dtype='int32')
J
Jiangxinz 已提交
185
                LSTM(error_input, pre_hidden, pre_cell, \
X
Xing Wu 已提交
186 187 188 189 190 191 192 193 194 195
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_input_type)

            def test_pre_hidden_type():
                error_pre_hidden = fluid.data(
                    name='error_pre_hidden',
                    shape=[None, hidden_size],
                    dtype='int32')
J
Jiangxinz 已提交
196
                LSTM(input, error_pre_hidden, pre_cell, \
X
Xing Wu 已提交
197 198 199 200 201 202 203 204 205 206
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_pre_hidden_type)

            def test_pre_cell_type():
                error_pre_cell = fluid.data(
                    name='error_pre_cell',
                    shape=[None, hidden_size],
                    dtype='int32')
J
Jiangxinz 已提交
207
                LSTM(input, pre_hidden, error_pre_cell, \
X
Xing Wu 已提交
208 209 210 211 212 213
                    seq_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)

            self.assertRaises(TypeError, test_pre_cell_type)


D
dangqingqing 已提交
214
class TestLstmOp(OpTest):
215 216 217
    def set_is_test(self):
        self.is_test = False

218
    def set_lod(self):
219
        self.lod = [[2, 3, 2]]
220 221

    def set_argument(self):
222
        self.set_is_test()
223
        self.set_lod()
224 225
        self.D = 16

226 227 228
        self.act_gate = 'sigmoid'
        self.act_cell = 'tanh'
        self.act_cand = 'tanh'
D
dangqingqing 已提交
229

D
dangqingqing 已提交
230
        self.has_initial_state = False
D
dangqingqing 已提交
231
        self.is_reverse = False
D
dangqingqing 已提交
232
        self.use_peepholes = True
D
dangqingqing 已提交
233 234

    def setUp(self):
235
        self.set_argument()
236
        self.op_type = 'lstm'
237 238
        T = sum(self.lod[0])
        N = len(self.lod[0])
D
dangqingqing 已提交
239

240
        x = np.random.normal(size=(T, 4 * self.D)).astype('float64')
D
dangqingqing 已提交
241 242 243 244 245 246
        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')
247
        w = np.random.normal(size=(self.D, 4 * self.D)).astype('float64')
D
dangqingqing 已提交
248 249 250 251
        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 已提交
252

D
dangqingqing 已提交
253 254
        w_b = b[:, 0:4 * self.D]
        w_c = b[:, 4 * self.D:] if self.use_peepholes else None
D
dangqingqing 已提交
255
        h, c = lstm(x, self.lod, h0, c0, w, w_b, w_c, self.is_reverse,
256 257
                    ACTIVATION[self.act_gate], ACTIVATION[self.act_cell],
                    ACTIVATION[self.act_cand])
258

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

D
dangqingqing 已提交
261
        self.inputs['Bias'] = b
262

D
dangqingqing 已提交
263 264 265
        if self.has_initial_state:
            self.inputs['H0'] = h0
            self.inputs['C0'] = c0
266

267 268 269 270
        self.outputs = {
            'Hidden': (h, self.lod),
            'Cell': (c, self.lod),
        }
271
        self.attrs = {
D
dangqingqing 已提交
272
            'use_peepholes': self.use_peepholes,
273 274 275
            'is_reverse': self.is_reverse,
            'gate_activation': self.act_gate,
            'cell_activation': self.act_cell,
276 277
            'candidate_activation': self.act_cand,
            'is_test': self.is_test
278 279
        }

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

D
dangqingqing 已提交
283
    def test_check_grad(self):
D
dangqingqing 已提交
284
        # TODO(qingqing) remove folowing lines after the check_grad is refined.
285
        N = len(self.lod[0])
D
dangqingqing 已提交
286 287 288
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
289
        self.check_grad(
H
hong 已提交
290 291 292
            ['Input', 'Weight', 'Bias'], ['Hidden'],
            max_relative_error=5e-4,
            check_dygraph=False)
293 294


295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
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]]


310 311 312 313 314 315 316 317 318
class TestLstmOpInference(TestLstmOp):
    def set_is_test(self):
        self.is_test = True

    # avoid checking gradient
    def test_check_grad(self):
        pass


319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
class TestLstmOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):

            def test_Variable():
                input_data = np.random.random((1, 2048)).astype("float32")
                fluid.layers.dynamic_lstm(
                    input=input_data, size=2048, use_peepholes=False)

            self.assertRaises(TypeError, test_Variable)

            def test_h_0():
                in_data = fluid.data(
                    name="input", shape=[None, 2048], dtype="float32")
                h = fluid.data(name="h", shape=[None, 512], dtype="int32")
                c = fluid.data(name="c", shape=[None, 512], dtype="float32")
                fluid.layers.dynamic_lstm(
                    input=in_data, size=2048, use_peepholes=False, h_0=h, c_0=c)

            self.assertRaises(TypeError, test_h_0)

            def test_c_0():
                in_data_ = fluid.data(
                    name="input_", shape=[None, 2048], dtype="float32")
                h_ = fluid.data(name="h_", shape=[None, 512], dtype="float32")
                c_ = fluid.data(name="c_", shape=[None, 512], dtype="int32")
                fluid.layers.dynamic_lstm(
                    input=in_data_,
                    size=2048,
                    use_peepholes=False,
                    h_0=h_,
                    c_0=c_)

            self.assertRaises(TypeError, test_c_0)


355 356
# class TestLstmOpHasInitial(TestLstmOp):
#     def set_argument(self):
357
#         self.lod = [[2, 3, 2]]
358 359 360 361 362 363 364 365 366 367 368 369
#         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.
370
#         N = len(self.lod[0])
371 372 373 374 375 376 377 378
#         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):
379
#         N = len(self.lod[0])
380 381 382 383 384 385 386 387 388
#         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):
389
#         N = len(self.lod[0])
390 391 392 393 394 395 396 397 398
#         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):
399
#         N = len(self.lod[0])
400 401 402 403 404 405 406 407 408
#         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):
409
#         N = len(self.lod[0])
410 411 412 413 414 415 416 417 418
#         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):
419
#         N = len(self.lod[0])
420 421 422 423 424 425 426 427 428 429
#         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):
430
#         self.lod = [[2, 3, 2]]
431 432 433 434 435 436 437 438 439 440 441 442
#         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):
443
#         self.lod = [[2, 3, 2]]
444 445 446 447 448 449 450 451 452
#         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
453 454

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