test_recurrent_op.py 14.4 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.

Y
Yan Chunwei 已提交
15
import unittest
S
superjom 已提交
16

Q
Qiao Longfei 已提交
17
import paddle.v2.fluid.layers as layers
Q
qiaolongfei 已提交
18
from paddle.v2.fluid.framework import Program, grad_var_name
Q
Qiao Longfei 已提交
19
from paddle.v2.fluid.executor import Executor
F
fengjiayi 已提交
20
from paddle.v2.fluid.backward import append_backward
Y
Yu Yang 已提交
21
import numpy as np
Q
Qiao Longfei 已提交
22
import paddle.v2.fluid.core as core
S
fix res  
superjom 已提交
23 24


Y
Yu Yang 已提交
25 26 27 28
class PyRNNBase(object):
    def __init__(self, input_shape, output_shape):
        self.x = np.ones(shape=input_shape).astype("float32")
        self.y = np.zeros(shape=output_shape).astype("float32")
S
superjom 已提交
29

30 31
    def step(self, step_id, x):
        raise NotImplementedError
S
superjom 已提交
32 33 34

    def forward(self):
        for step_id in range(self.x.shape[0]):
Y
Yu Yang 已提交
35 36
            self.step(step_id, self.x[step_id])
        return np.array([np.mean(self.y)])
S
superjom 已提交
37 38 39 40

    def segment_inputs(self):
        return [self.x[i] for i in range(self.x.shape[0])]

Y
Yu Yang 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

class PySimpleRNN1(PyRNNBase):
    def __init__(self, input_shape, output_shape):
        super(PySimpleRNN1, self).__init__(input_shape, output_shape)

        seq_len, batch_size, input_dim = input_shape
        self.h_boot = np.random.normal(size=(batch_size,
                                             input_dim)).astype("float32")

        self.scale = 1.0 / 2.0
        men_dim = (seq_len, batch_size, input_dim)
        self.mems = np.zeros(shape=men_dim).astype("float32")

    def step(self, step_id, x):
        if step_id == 0:
            pre_mem = self.h_boot
        else:
            pre_mem = self.mems[step_id - 1]
        self.mems[step_id] = (pre_mem + x) * self.scale
        self.y[step_id] = self.mems[step_id]


class PySimpleRNN2(PyRNNBase):
    def __init__(self, input_shape, output_shape):
        super(PySimpleRNN2, self).__init__(input_shape, output_shape)

        seq_len, batch_size, input_dim = input_shape
        self.W = np.random.normal(size=(input_dim, input_dim)).astype("float32")
        self.U = np.random.normal(size=(input_dim, input_dim)).astype("float32")
        self.h_boot = np.ones(shape=(batch_size, input_dim)).astype("float32")

        men_dim = (seq_len, batch_size, input_dim)
        self.mems = np.zeros(shape=men_dim).astype("float32")
S
superjom 已提交
74 75 76

    def step(self, step_id, x):
        if step_id > 0:
S
fix res  
superjom 已提交
77
            pre_mem = self.mems[step_id - 1]
S
superjom 已提交
78 79
        else:
            pre_mem = self.h_boot
Q
qiaolongfei 已提交
80 81
        xW = np.matmul(x, self.W).astype("float32")
        hU = np.matmul(pre_mem, self.U).astype("float32")
S
superjom 已提交
82

Y
Yu Yang 已提交
83 84
        def py_sigmoid(x):
            return 1. / (1. + np.exp(-x))
S
fix res  
superjom 已提交
85

Y
Yu Yang 已提交
86 87
        self.mems[step_id] = py_sigmoid(xW + hU)
        self.y[step_id] = self.mems[step_id]
Y
Yan Chunwei 已提交
88 89


Y
Yu Yang 已提交
90 91 92
def create_tensor(np_data, place):
    tensor = core.LoDTensor()
    tensor.set(np_data, place)
Y
Yan Chunwei 已提交
93 94 95
    return tensor


Y
Yu Yang 已提交
96
class RecurrentOpTest1(unittest.TestCase):
Y
Yan Chunwei 已提交
97 98 99
    '''
    Test RNNOp
    equation:
Y
Yu Yang 已提交
100
        h_t = ( x_t + h_{t-1} ) / scale
Y
Yan Chunwei 已提交
101 102 103 104 105
    vars:
        - x
    memories:
        - h
    outputs:
Y
Yu Yang 已提交
106
        - h
Y
Yan Chunwei 已提交
107 108
    '''

Y
Yu Yang 已提交
109 110 111 112
    input_dim = 2
    batch_size = 1
    sent_len = 1

113 114 115
    def setup_program(self):
        self.main_program = Program()
        self.startup_program = Program()
Y
Yu Yang 已提交
116
        self.p_info = {
117 118
            "main_program": self.main_program,
            "startup_program": self.startup_program
Y
Yu Yang 已提交
119 120
        }
        self.place = core.CPUPlace()
Y
Yan Chunwei 已提交
121

S
superjom 已提交
122
    def setUp(self):
123
        self.setup_program()
Y
Yu Yang 已提交
124
        self.data_field = {"x", "h_boot"}
Y
Yan Chunwei 已提交
125

Y
Yu Yang 已提交
126 127 128 129
        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.py_rnn = PySimpleRNN1(self.input_shape, self.output_shape)

130
        self.output = layers.mean(x=self.create_rnn_op(), **self.p_info)
Y
Yan Chunwei 已提交
131 132

    def create_rnn_op(self):
133
        x = layers.data(
Y
Yu Yang 已提交
134
            shape=[self.sent_len, self.batch_size, self.input_dim],
F
fengjiayi 已提交
135
            dtype='float32',
Y
Yu Yang 已提交
136 137 138
            name='x',
            append_batch_size=False,
            **self.p_info)
Y
Yu Yang 已提交
139
        x.stop_gradient = False
140
        h_boot = layers.data(
Y
Yu Yang 已提交
141
            shape=[self.input_dim],
F
fengjiayi 已提交
142
            dtype='float32',
Y
Yu Yang 已提交
143 144
            name='h_boot',
            **self.p_info)
Y
Yu Yang 已提交
145
        h_boot.stop_gradient = False
Y
Yu Yang 已提交
146

147
        rnn = layers.StaticRNN(main_program=self.main_program)
Y
Yu Yang 已提交
148 149 150 151
        with rnn.step():
            h_pre = rnn.memory(init=h_boot)
            x_t = rnn.step_input(x)

152 153
            h = layers.scale(
                x=layers.elementwise_add(
Y
Yu Yang 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
                    x=h_pre, y=x_t, **self.p_info),
                scale=self.py_rnn.scale,
                **self.p_info)

            rnn.update_memory(h_pre, h)
            rnn.output(h)

        return rnn()

    def forward(self):
        self.feed_map = {
            x: create_tensor(getattr(self.py_rnn, x), self.place)
            for x in self.data_field
        }
        exe = Executor(self.place)
169
        out = exe.run(self.main_program,
Y
Yu Yang 已提交
170 171 172
                      feed=self.feed_map,
                      fetch_list=[self.output])

D
dzhwinter 已提交
173
        return out[0]
Y
Yu Yang 已提交
174 175 176 177 178 179 180

    def backward(self):
        self.feed_map = {
            x: create_tensor(getattr(self.py_rnn, x), self.place)
            for x in self.data_field
        }
        fetch_list = [
Q
qiaolongfei 已提交
181
            self.main_program.global_block().var(grad_var_name(x))
Y
Yu Yang 已提交
182 183 184 185
            for x in self.data_field
        ]

        exe = Executor(self.place)
186 187
        return exe.run(self.main_program,
                       feed=self.feed_map,
D
dzhwinter 已提交
188 189
                       fetch_list=fetch_list,
                       return_numpy=False)
Y
Yu Yang 已提交
190 191 192 193

    def test_backward(self):
        self.check_forward()

F
fengjiayi 已提交
194
        append_backward(self.output)
Y
Yu Yang 已提交
195 196 197 198 199 200 201 202 203 204 205

        ana_grad = [np.array(x) for x in self.backward()]

        num_grad = self.get_numerical_gradient()
        for idx, name in enumerate(self.data_field):
            self.assertEqual(num_grad[idx].shape, ana_grad[idx].shape)
            self.assertTrue(
                np.isclose(
                    num_grad[idx], ana_grad[idx], rtol=0.1).all())

    def check_forward(self):
S
superjom 已提交
206
        print 'test recurrent op forward'
S
superjom 已提交
207 208 209 210 211 212
        pd_output = self.forward()
        py_output = self.py_rnn.forward()
        print 'pd_output', pd_output
        print
        print 'py_output', py_output
        self.assertEqual(pd_output.shape, py_output.shape)
S
superjom 已提交
213
        self.assertTrue(np.isclose(pd_output, py_output, rtol=0.1).all())
Y
Yan Chunwei 已提交
214

Y
Yu Yang 已提交
215 216 217 218 219 220 221 222 223
    def get_numerical_gradient(self, delta=0.005):
        dloss_dout = 1.0
        feed_list = [getattr(self.py_rnn, x) for x in self.data_field]
        grad_list = [np.zeros_like(x) for x in feed_list]
        for feed, grad in zip(feed_list, grad_list):
            for f, g in np.nditer([feed, grad], op_flags=['readwrite']):
                o = float(f)
                f[...] = o + delta
                y_pos = self.forward()
S
fix res  
superjom 已提交
224

Y
Yu Yang 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                f[...] = o - delta
                y_neg = self.forward()

                f[...] = o
                dout_dfeed = (y_pos - y_neg) / (delta * 2)
                g[...] = dout_dfeed[0]

        return grad_list


class RecurrentOpTest2(RecurrentOpTest1):
    '''
    Test RNNOp
    equation:
        h_t = \sigma (W x_t + U h_{t-1})
    weights:
        - W
        - U
    vars:
        - x
    memories:
        - h
    outputs:
       - h
    '''

    input_dim = 2
    batch_size = 10
    sent_len = 2

    def setUp(self):
256
        self.setup_program()
Y
Yu Yang 已提交
257 258 259 260 261 262 263

        self.data_field = {"x", "h_boot", "W", "U"}

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.py_rnn = PySimpleRNN2(self.input_shape, self.output_shape)

264
        self.output = layers.mean(x=self.create_rnn_op(), **self.p_info)
Y
Yu Yang 已提交
265 266

    def create_rnn_op(self):
267
        x = layers.data(
Y
Yu Yang 已提交
268
            shape=[self.sent_len, self.batch_size, self.input_dim],
F
fengjiayi 已提交
269
            dtype='float32',
Y
Yu Yang 已提交
270 271 272
            name='x',
            append_batch_size=False,
            **self.p_info)
Y
Yu Yang 已提交
273
        x.stop_gradient = False
274
        h_boot = layers.data(
Y
Yu Yang 已提交
275
            shape=[self.input_dim],
F
fengjiayi 已提交
276
            dtype='float32',
Y
Yu Yang 已提交
277 278
            name='h_boot',
            **self.p_info)
Y
Yu Yang 已提交
279
        h_boot.stop_gradient = False
Y
Yu Yang 已提交
280

281
        rnn = layers.StaticRNN(main_program=self.main_program)
Y
Yu Yang 已提交
282 283 284 285
        with rnn.step():
            h_pre = rnn.memory(init=h_boot)
            x_t = rnn.step_input(x)

286 287
            temp_l = layers.fc(input=x_t,
                               size=self.input_dim,
Y
Yu Yang 已提交
288
                               param_attr='W',
289 290 291 292
                               bias_attr=False,
                               **self.p_info)
            temp_r = layers.fc(input=h_pre,
                               size=self.input_dim,
Y
Yu Yang 已提交
293
                               param_attr='U',
294 295 296 297 298
                               bias_attr=False,
                               **self.p_info)

            h = layers.sigmoid(
                x=layers.elementwise_add(
Y
Yu Yang 已提交
299 300 301 302 303 304 305 306 307
                    x=temp_l, y=temp_r, **self.p_info),
                **self.p_info)

            rnn.update_memory(h_pre, h)
            rnn.output(h)

        return rnn()


308
class RecurrentOpMultipleMemoryTest(RecurrentOpTest1):
Y
Yu Yang 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    '''
    Test RNNOp with two memories
    equation:
        h_1 = h_pre_1
        h_2 = h_pre_2
        y = h_1 + h_2
    vars:
        - x
    memories:
        - h_1, h_2
    outputs:
       - y
    '''

    class PySimpleRNN3(PyRNNBase):
        def __init__(self, input_shape, output_shape):
325 326
            super(RecurrentOpMultipleMemoryTest.PySimpleRNN3, self).__init__(
                input_shape, output_shape)
Y
Yu Yang 已提交
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

            seq_len, batch_size, input_dim = input_shape
            self.h_boot1 = np.random.normal(size=(batch_size,
                                                  input_dim)).astype("float32")
            self.h_boot2 = np.random.normal(size=(batch_size,
                                                  input_dim)).astype("float32")

            men_dim = (seq_len, batch_size, input_dim)
            self.mems1 = np.zeros(shape=men_dim).astype("float32")
            self.mems2 = np.zeros(shape=men_dim).astype("float32")

        def step(self, step_id, x):
            if step_id == 0:
                pre_mem1 = self.h_boot1
                pre_mem2 = self.h_boot2
            else:
                pre_mem1 = self.mems1[step_id - 1]
                pre_mem2 = self.mems2[step_id - 1]
            self.mems1[step_id] = pre_mem1
            self.mems2[step_id] = pre_mem2
            self.y[step_id] = self.mems1[step_id] + self.mems2[step_id] + x

    input_dim = 1
    batch_size = 1
    sent_len = 2

    def setUp(self):
354
        self.setup_program()
Y
Yu Yang 已提交
355 356 357 358 359

        self.data_field = {"x", "h_boot1", "h_boot2"}

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
360 361
        self.py_rnn = RecurrentOpMultipleMemoryTest.PySimpleRNN3(
            self.input_shape, self.output_shape)
Y
Yu Yang 已提交
362

363
        self.output = layers.mean(x=self.create_rnn_op(), **self.p_info)
Y
Yu Yang 已提交
364 365

    def create_rnn_op(self):
366
        x = layers.data(
Y
Yu Yang 已提交
367
            shape=[self.sent_len, self.batch_size, self.input_dim],
F
fengjiayi 已提交
368
            dtype='float32',
Y
Yu Yang 已提交
369 370 371
            name='x',
            append_batch_size=False,
            **self.p_info)
Y
Yu Yang 已提交
372
        x.stop_gradient = False
373
        h_boot1 = layers.data(
Y
Yu Yang 已提交
374
            shape=[self.batch_size, self.input_dim],
F
fengjiayi 已提交
375
            dtype='float32',
Y
Yu Yang 已提交
376 377 378
            name='h_boot1',
            append_batch_size=False,
            **self.p_info)
Y
Yu Yang 已提交
379
        h_boot1.stop_gradient = False
380
        h_boot2 = layers.data(
Y
Yu Yang 已提交
381
            shape=[self.batch_size, self.input_dim],
F
fengjiayi 已提交
382
            dtype='float32',
Y
Yu Yang 已提交
383 384 385
            name='h_boot2',
            append_batch_size=False,
            **self.p_info)
Y
Yu Yang 已提交
386
        h_boot2.stop_gradient = False
Y
Yu Yang 已提交
387

388
        rnn = layers.StaticRNN(main_program=self.main_program)
Y
Yu Yang 已提交
389 390 391 392 393
        with rnn.step():
            h_pre1 = rnn.memory(init=h_boot1)
            h_pre2 = rnn.memory(init=h_boot2)
            x_t = rnn.step_input(x)

394 395 396
            mem1 = layers.scale(x=h_pre1, scale=1.0, **self.p_info)
            mem2 = layers.scale(x=h_pre2, scale=1.0, **self.p_info)
            out = layers.sums(input=[mem1, x_t, mem2], **self.p_info)
Y
Yu Yang 已提交
397 398 399 400 401 402

            rnn.update_memory(h_pre1, mem1)
            rnn.update_memory(h_pre2, mem2)
            rnn.output(out)

        return rnn()
S
init  
superjom 已提交
403 404


405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
class RecurrentOpNoMemBootTest(RecurrentOpTest1):
    '''
    Test RNNOp with two memories
    equation:
        mem = x + mem_pre
        y = mem
    vars:
        - x
    memories:
        - mem
    outputs:
       - y
    '''

    class PySimpleRNN4(PyRNNBase):
        def __init__(self, input_shape, output_shape):
            super(RecurrentOpNoMemBootTest.PySimpleRNN4, self).__init__(
                input_shape, output_shape)
            men_dim = input_shape
            self.mems = np.zeros(shape=men_dim).astype("float32")

        def step(self, step_id, x):
            if step_id == 0:
                pre_mem = np.zeros_like(x)
            else:
                pre_mem = self.mems[step_id - 1]
            self.mems[step_id] = pre_mem + x
            self.y[step_id] = self.mems[step_id]

    input_dim = 1
    batch_size = 1
    sent_len = 2

    def setUp(self):
        self.setup_program()

        self.data_field = {"x"}

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.py_rnn = RecurrentOpNoMemBootTest.PySimpleRNN4(self.input_shape,
                                                            self.output_shape)
        self.output = layers.mean(x=self.create_rnn_op(), **self.p_info)
        print self.main_program

    def create_rnn_op(self):
        x = layers.data(
            shape=[self.sent_len, self.batch_size, self.input_dim],
F
fengjiayi 已提交
453
            dtype='float32',
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            name='x',
            append_batch_size=False,
            **self.p_info)
        x.stop_gradient = False

        rnn = layers.StaticRNN(main_program=self.main_program)
        with rnn.step():
            mem_pre = rnn.memory(shape=[-1, self.input_dim], batch_ref=x)
            x_t = rnn.step_input(x)
            mem = layers.elementwise_add(x=mem_pre, y=x_t, **self.p_info)
            rnn.update_memory(mem_pre, mem)
            rnn.output(mem)

        return rnn()


Y
Yan Chunwei 已提交
470 471
if __name__ == '__main__':
    unittest.main()