test_lstmp_op.py 10.5 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
#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 numpy as np
16
import test_lstm_op as LstmTest
17

18
ACTIVATION = {
19 20 21 22
    'identity': LstmTest.identity,
    'sigmoid': LstmTest.sigmoid,
    'tanh': LstmTest.tanh,
    'relu': LstmTest.relu
23 24 25 26 27 28 29 30 31
}


# LSTM with recurrent projection Layer
def lstmp(
        input,  # T x 4D
        lod,  # 1 x N
        h0=None,  # N x D
        c0=None,  # N x D
32
        w_r=None,  # P x 4D
33 34 35 36 37 38
        w_rh=None,  # D x P
        w_b=None,  # 1 x 4D
        w_c=None,  # 1 x 3D
        is_reverse=False,
        act_gate=None,
        act_cell=None,
39
        act_cand=None,
40 41 42
        act_proj=None):
    def _step(x, w_r, w_rh, w_c, r_pre, c_pre, act_gate, act_cell, act_cand,
              act_proj):
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        g = np.dot(r_pre, w_r)  # 1 x 4D
        g = g + x
        g = np.reshape(g, (1, g.size))
        c, g_i, g_f, g_o = np.split(g, 4, axis=1)
        if w_c is None:
            g_i = act_gate(g_i)  # 1 x D
            g_f = act_gate(g_f)  # 1 x D
        else:
            w_ic, w_fc, _ = np.split(w_c, 3, axis=1)
            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
        c = g_f * c_pre + g_i * act_cand(c)  # 1 x D

        if w_c is None:
            g_o = act_gate(g_o)  # 1 x D
        else:
            _, _, w_oc = np.split(w_c, 3, axis=1)
            g_o = act_gate(g_o + w_oc * c)  # 1 x D
        h = g_o * act_cell(c)
        # projection
        r = np.dot(h, w_rh)
64
        r = act_proj(r)
65 66
        return r, c

67
    def _reverse(x, offset):
68
        y = np.zeros_like(x)
69 70
        for i in range(len(offset) - 1):
            b, e = offset[i], offset[i + 1]
71 72 73
            y[b:e, :] = np.flip(x[b:e, :], 0)
        return y

74 75 76 77
    offset = [0]
    for l in lod[0]:
        offset.append(offset[-1] + l)
    batch_size = len(lod[0])
78 79 80 81 82 83 84 85
    # recurrent projection state
    projection = []
    cell = []
    input = _reverse(input, offset) if is_reverse else input
    if w_b is not None:
        input = input + np.tile(w_b, (offset[-1], 1))
    for i in range(batch_size):
        # compute one sequence
86
        seq_len = lod[0][i]
87 88
        x = input[offset[i]:offset[i + 1], :]
        r_pre = np.dot(h0[i], w_rh)  # 1 x P
89
        r_pre = act_proj(r_pre)
90 91 92 93
        c_pre = c0[i]  # 1 x D
        for j in range(seq_len):
            # compute one step
            r_pre, c_pre = _step(x[j], w_r, w_rh, w_c, r_pre, c_pre, act_gate,
94
                                 act_cell, act_cand, act_proj)
95 96 97 98 99 100 101 102 103 104 105 106 107 108
            projection.append(r_pre.flatten())
            cell.append(c_pre.flatten())

    projection = np.array(projection).astype('float64')
    cell = np.array(cell).astype('float64')

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

    assert projection.shape == (input.shape[0], w_r.shape[0])  # T x P
    assert cell.shape == (input.shape[0], input.shape[1] / 4)  # T x D
    return projection, cell


109
class TestLstmpOp(LstmTest.TestLstmOp):
Y
Yibing Liu 已提交
110 111 112 113
    def reset_argument(self):
        pass

    def setUp(self):
114
        self.set_argument()
115 116
        # projection size
        self.P = 10
117
        self.act_proj = self.act_cell
118

Y
Yibing Liu 已提交
119
        self.reset_argument()
120 121
        self.op_type = 'lstmp'

122 123
        T = sum(self.lod[0])
        N = len(self.lod[0])
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

        x = np.random.normal(size=(T, 4 * self.D)).astype('float64')
        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')
        w = np.random.normal(size=(self.P, 4 * self.D)).astype('float64')
        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')

        w_b = b[:, 0:4 * self.D]
        w_c = b[:, 4 * self.D:] if self.use_peepholes else None
        w_rh = np.random.normal(size=(self.D, self.P)).astype('float64')
        r, c = lstmp(x, self.lod, h0, c0, w, w_rh, w_b, w_c, self.is_reverse,
142 143
                     ACTIVATION[self.act_gate], ACTIVATION[self.act_cell],
                     ACTIVATION[self.act_cand], ACTIVATION[self.act_proj])
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

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

        self.inputs['Bias'] = b

        if self.has_initial_state:
            self.inputs['H0'] = h0
            self.inputs['C0'] = c0

        self.outputs = {
            'Projection': (r, self.lod),
            'Cell': (c, self.lod),
        }
        self.attrs = {
            'use_peepholes': self.use_peepholes,
            'is_reverse': self.is_reverse,
            'gate_activation': self.act_gate,
            'cell_activation': self.act_cell,
Y
Yibing Liu 已提交
162
            'candidate_activation': self.act_cand,
163
            'proj_activation': self.act_proj
164 165 166 167 168 169 170
        }

    def test_check_output(self):
        self.check_output(atol=1e-8)

    def test_check_grad(self):
        # TODO(qingqing) remove folowing lines after the check_grad is refined.
171
        N = len(self.lod[0])
172
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
173
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
174
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
175 176 177
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
178 179
            ['Input', 'Weight', 'ProjWeight', 'Bias'], ['Projection'],
            max_relative_error=1e-2)
180 181


182
class TestLstmpOpHasInitial(TestLstmpOp):
Y
Yibing Liu 已提交
183
    def reset_argument(self):
184 185 186 187
        self.has_initial_state = True

    def test_check_grad(self):
        # TODO(qingqing) remove folowing lines after the check_grad is refined.
188
        N = len(self.lod[0])
189
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
190
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
191
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
192 193 194
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
195 196 197
            ['Input', 'Weight', 'ProjWeight', 'Bias', 'H0', 'C0'],
            ['Projection'],
            max_relative_error=1e-2)
198 199

    def test_check_grad_ingore_bias(self):
200
        N = len(self.lod[0])
201
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
202
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
203
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
204 205 206
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
207 208
            ['Input', 'ProjWeight', 'Weight'], ['Projection'],
            max_relative_error=1e-2,
209 210 211
            no_grad_set=set('Bias'))

    def test_check_grad_ingore_weight(self):
212
        N = len(self.lod[0])
213
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
214
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
215
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
216 217 218
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
219 220
            ['Input', 'ProjWeight', 'Bias'], ['Projection'],
            max_relative_error=1e-2,
221 222
            no_grad_set=set('Weight'))

223
    def test_check_grad_ingore_proj_weight(self):
224
        N = len(self.lod[0])
225 226 227 228 229 230 231 232 233 234
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
            ['Input', 'Weight', 'Bias'], ['Projection'],
            max_relative_error=1e-2,
            no_grad_set=set('ProjWeight'))

235
    def test_check_grad_ingore_input(self):
236
        N = len(self.lod[0])
237
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
238
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
239
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
240 241 242
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
243 244
            ['Weight', 'ProjWeight', 'Bias'], ['Projection'],
            max_relative_error=1e-2,
245 246 247
            no_grad_set=set('Input'))

    def test_check_grad_ingore_h0(self):
248
        N = len(self.lod[0])
249
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
250
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
251
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
252 253 254
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
255 256
            ['Input', 'Weight', 'ProjWeight', 'Bias', 'C0'], ['Projection'],
            max_relative_error=1e-2,
257 258 259
            no_grad_set=set('H0'))

    def test_check_grad_ingore_c0(self):
260
        N = len(self.lod[0])
261
        self.outputs['OrderedP0'] = np.zeros((N, self.P)).astype('float64')
262
        self.outputs['BatchGate'] = np.zeros((N, 4 * self.D)).astype('float64')
263
        self.outputs['BatchHidden'] = np.zeros((N, self.D)).astype('float64')
264 265 266
        self.outputs['BatchCellPreAct'] = np.zeros(
            (N, self.D)).astype('float64')
        self.check_grad(
267 268
            ['Input', 'Weight', 'ProjWeight', 'Bias', 'H0'], ['Projection'],
            max_relative_error=1e-2,
269 270 271
            no_grad_set=set('C0'))


272
class TestLstmpOpRerverse(TestLstmpOp):
Y
Yibing Liu 已提交
273
    def reset_argument(self):
274 275 276
        self.is_reverse = True


277
class TestLstmpOpNotUsePeepholes(TestLstmpOp):
Y
Yibing Liu 已提交
278
    def reset_argument(self):
279 280 281
        self.use_peepholes = False


282
class TestLstmpOpLinearProjection(TestLstmpOp):
Y
Yibing Liu 已提交
283
    def reset_argument(self):
284
        self.act_proj = 'identity'
Y
Yibing Liu 已提交
285 286


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