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

Y
Yan Chunwei 已提交
15
import unittest
16 17 18

import numpy as np

19
import paddle
C
chengduo 已提交
20
import paddle.fluid as fluid
21
import paddle.fluid.core as core
22
import paddle.fluid.layers as layers
23
from paddle.fluid import ParamAttr
24
from paddle.fluid.backward import append_backward
25 26
from paddle.fluid.executor import Executor
from paddle.fluid.framework import Program, grad_var_name
S
fix res  
superjom 已提交
27

28 29
np.random.seed(123)

S
fix res  
superjom 已提交
30

31
class PyRNNBase:
Y
Yu Yang 已提交
32 33 34
    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 已提交
35

36 37
    def step(self, step_id, x):
        raise NotImplementedError
S
superjom 已提交
38 39 40

    def forward(self):
        for step_id in range(self.x.shape[0]):
Y
Yu Yang 已提交
41 42
            self.step(step_id, self.x[step_id])
        return np.array([np.mean(self.y)])
S
superjom 已提交
43 44 45 46

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

Y
Yu Yang 已提交
47 48 49

class PySimpleRNN1(PyRNNBase):
    def __init__(self, input_shape, output_shape):
50
        super().__init__(input_shape, output_shape)
Y
Yu Yang 已提交
51 52

        seq_len, batch_size, input_dim = input_shape
53 54 55
        self.h_boot = np.random.normal(size=(batch_size, input_dim)).astype(
            "float32"
        )
Y
Yu Yang 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

        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):
72
        super().__init__(input_shape, output_shape)
Y
Yu Yang 已提交
73 74

        seq_len, batch_size, input_dim = input_shape
75 76
        self.W = np.ones(shape=(input_dim, input_dim)).astype("float32")
        self.U = np.zeros(shape=(input_dim, input_dim)).astype("float32")
Y
Yu Yang 已提交
77 78 79 80
        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 已提交
81 82 83

    def step(self, step_id, x):
        if step_id > 0:
S
fix res  
superjom 已提交
84
            pre_mem = self.mems[step_id - 1]
S
superjom 已提交
85 86
        else:
            pre_mem = self.h_boot
Q
qiaolongfei 已提交
87 88
        xW = np.matmul(x, self.W).astype("float32")
        hU = np.matmul(pre_mem, self.U).astype("float32")
S
superjom 已提交
89

Y
Yu Yang 已提交
90
        def py_sigmoid(x):
91
            return 1.0 / (1.0 + np.exp(-x))
S
fix res  
superjom 已提交
92

Y
Yu Yang 已提交
93 94
        self.mems[step_id] = py_sigmoid(xW + hU)
        self.y[step_id] = self.mems[step_id]
Y
Yan Chunwei 已提交
95 96


Y
Yu Yang 已提交
97 98 99
def create_tensor(np_data, place):
    tensor = core.LoDTensor()
    tensor.set(np_data, place)
Y
Yan Chunwei 已提交
100 101 102
    return tensor


Y
Yu Yang 已提交
103
class RecurrentOpTest1(unittest.TestCase):
Y
Yan Chunwei 已提交
104 105 106
    '''
    Test RNNOp
    equation:
Y
Yu Yang 已提交
107
        h_t = ( x_t + h_{t-1} ) / scale
Y
Yan Chunwei 已提交
108 109 110 111 112
    vars:
        - x
    memories:
        - h
    outputs:
Y
Yu Yang 已提交
113
        - h
Y
Yan Chunwei 已提交
114 115
    '''

Y
Yu Yang 已提交
116 117 118 119
    input_dim = 2
    batch_size = 1
    sent_len = 1

120 121 122
    def setup_program(self):
        self.main_program = Program()
        self.startup_program = Program()
Y
Yu Yang 已提交
123
        self.place = core.CPUPlace()
Y
Yan Chunwei 已提交
124

S
superjom 已提交
125
    def setUp(self):
126
        self.setup_program()
127 128
        self.feed_data_field = {"x", "h_boot"}
        self.grad_data_field = self.feed_data_field
Y
Yan Chunwei 已提交
129

Y
Yu Yang 已提交
130 131 132 133
        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)

C
chengduo 已提交
134
        with fluid.program_guard(self.main_program, self.startup_program):
135
            self.output = paddle.mean(self.create_rnn_op())
Y
Yan Chunwei 已提交
136 137

    def create_rnn_op(self):
G
GGBond8488 已提交
138
        x = paddle.static.data(
139 140 141 142
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
            name='x',
        )
Y
Yu Yang 已提交
143
        x.stop_gradient = False
G
GGBond8488 已提交
144 145
        h_boot = paddle.static.data(
            shape=[-1, self.input_dim], dtype='float32', name='h_boot'
146
        )
Y
Yu Yang 已提交
147
        h_boot.stop_gradient = False
Y
Yu Yang 已提交
148

C
chengduo 已提交
149
        rnn = layers.StaticRNN()
Y
Yu Yang 已提交
150 151 152 153
        with rnn.step():
            h_pre = rnn.memory(init=h_boot)
            x_t = rnn.step_input(x)

2
201716010711 已提交
154
            h = paddle.scale(
155
                x=paddle.add(x=h_pre, y=x_t),
156 157
                scale=self.py_rnn.scale,
            )
Y
Yu Yang 已提交
158 159 160 161 162 163 164 165 166

            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)
167
            for x in self.feed_data_field
Y
Yu Yang 已提交
168 169
        }
        exe = Executor(self.place)
170 171 172
        out = exe.run(
            self.main_program, feed=self.feed_map, fetch_list=[self.output]
        )
Y
Yu Yang 已提交
173

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

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

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

194
    def test_backward(self, rtol=0.01):
Y
Yu Yang 已提交
195 196
        self.check_forward()

C
chengduo 已提交
197 198
        with fluid.program_guard(self.main_program, self.startup_program):
            append_backward(self.output)
Y
Yu Yang 已提交
199 200 201 202

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

        num_grad = self.get_numerical_gradient()
203
        for idx, name in enumerate(self.grad_data_field):
Y
Yu Yang 已提交
204
            self.assertEqual(num_grad[idx].shape, ana_grad[idx].shape)
205 206 207 208 209
            np.testing.assert_allclose(
                num_grad[idx],
                ana_grad[idx],
                rtol=rtol,
                atol=1e-8,
210 211 212 213 214 215 216 217 218 219 220 221
                err_msg='num_grad ('
                + name
                + ') has diff at '
                + str(self.place)
                + '\nExpect '
                + str(num_grad[idx])
                + '\n'
                + 'But Got'
                + str(ana_grad[idx])
                + ' in class '
                + self.__class__.__name__,
            )
Y
Yu Yang 已提交
222 223

    def check_forward(self):
S
superjom 已提交
224 225 226
        pd_output = self.forward()
        py_output = self.py_rnn.forward()
        self.assertEqual(pd_output.shape, py_output.shape)
227
        np.testing.assert_allclose(pd_output, py_output, rtol=0.01)
Y
Yan Chunwei 已提交
228

Y
Yu Yang 已提交
229 230
    def get_numerical_gradient(self, delta=0.005):
        dloss_dout = 1.0
231
        feed_list = [getattr(self.py_rnn, x) for x in self.grad_data_field]
Y
Yu Yang 已提交
232 233 234 235 236 237
        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 已提交
238

Y
Yu Yang 已提交
239 240 241 242 243 244 245 246 247 248 249
                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):
250
    r'''
Y
Yu Yang 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    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):
270
        self.setup_program()
Y
Yu Yang 已提交
271

272 273
        self.feed_data_field = {"x", "h_boot", "W", "U"}
        self.grad_data_field = self.feed_data_field
Y
Yu Yang 已提交
274 275 276 277 278

        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)

C
chengduo 已提交
279
        with fluid.program_guard(self.main_program, self.startup_program):
280
            self.output = paddle.mean(self.create_rnn_op())
Y
Yu Yang 已提交
281 282

    def create_rnn_op(self):
G
GGBond8488 已提交
283
        x = paddle.static.data(
284 285 286 287
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
            name='x',
        )
Y
Yu Yang 已提交
288
        x.stop_gradient = False
G
GGBond8488 已提交
289 290
        h_boot = paddle.static.data(
            shape=[-1, self.input_dim], dtype='float32', name='h_boot'
291
        )
Y
Yu Yang 已提交
292
        h_boot.stop_gradient = False
Y
Yu Yang 已提交
293

C
chengduo 已提交
294
        rnn = layers.StaticRNN()
Y
Yu Yang 已提交
295 296 297 298
        with rnn.step():
            h_pre = rnn.memory(init=h_boot)
            x_t = rnn.step_input(x)

C
Charles-hit 已提交
299 300
            temp_l = paddle.static.nn.fc(
                x=x_t,
301
                size=self.input_dim,
C
Charles-hit 已提交
302
                weight_attr=ParamAttr(
303
                    name='W',
304 305 306 307
                    initializer=fluid.initializer.ConstantInitializer(1.0),
                ),
                bias_attr=False,
            )
C
Charles-hit 已提交
308 309
            temp_r = paddle.static.nn.fc(
                x=h_pre,
310
                size=self.input_dim,
C
Charles-hit 已提交
311
                weight_attr=ParamAttr(
312
                    name='U',
313 314 315 316
                    initializer=fluid.initializer.ConstantInitializer(0.0),
                ),
                bias_attr=False,
            )
317

318
            h = paddle.nn.functional.sigmoid(x=paddle.add(x=temp_l, y=temp_r))
Y
Yu Yang 已提交
319 320 321 322 323 324

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

        return rnn()

C
chengduo 已提交
325
    def test_backward(self):
326
        super().test_backward(rtol=0.01)
C
chengduo 已提交
327

Y
Yu Yang 已提交
328

329
class RecurrentOpMultipleMemoryTest(RecurrentOpTest1):
Y
Yu Yang 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    '''
    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):
346
            super().__init__(input_shape, output_shape)
Y
Yu Yang 已提交
347 348

            seq_len, batch_size, input_dim = input_shape
349 350 351 352 353 354
            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")
Y
Yu Yang 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

            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):
376
        self.setup_program()
Y
Yu Yang 已提交
377

378 379
        self.feed_data_field = {"x", "h_boot1", "h_boot2"}
        self.grad_data_field = self.feed_data_field
Y
Yu Yang 已提交
380 381 382

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
383
        self.py_rnn = RecurrentOpMultipleMemoryTest.PySimpleRNN3(
384 385
            self.input_shape, self.output_shape
        )
Y
Yu Yang 已提交
386

C
chengduo 已提交
387
        with fluid.program_guard(self.main_program, self.startup_program):
388
            self.output = paddle.mean(self.create_rnn_op())
Y
Yu Yang 已提交
389 390

    def create_rnn_op(self):
G
GGBond8488 已提交
391
        x = paddle.static.data(
392 393 394 395
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
            name='x',
        )
Y
Yu Yang 已提交
396
        x.stop_gradient = False
G
GGBond8488 已提交
397
        h_boot1 = paddle.static.data(
398 399 400 401
            shape=[self.batch_size, self.input_dim],
            dtype='float32',
            name='h_boot1',
        )
Y
Yu Yang 已提交
402
        h_boot1.stop_gradient = False
G
GGBond8488 已提交
403
        h_boot2 = paddle.static.data(
404 405 406 407
            shape=[self.batch_size, self.input_dim],
            dtype='float32',
            name='h_boot2',
        )
Y
Yu Yang 已提交
408
        h_boot2.stop_gradient = False
Y
Yu Yang 已提交
409

C
chengduo 已提交
410
        rnn = layers.StaticRNN()
Y
Yu Yang 已提交
411 412 413 414 415
        with rnn.step():
            h_pre1 = rnn.memory(init=h_boot1)
            h_pre2 = rnn.memory(init=h_boot2)
            x_t = rnn.step_input(x)

2
201716010711 已提交
416 417
            mem1 = paddle.scale(x=h_pre1, scale=1.0)
            mem2 = paddle.scale(x=h_pre2, scale=1.0)
C
chengduo 已提交
418
            out = layers.sums(input=[mem1, x_t, mem2])
Y
Yu Yang 已提交
419 420 421 422 423 424

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

        return rnn()
S
init  
superjom 已提交
425 426


427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
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):
443
            super().__init__(input_shape, output_shape)
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
            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()

462 463
        self.feed_data_field = {"x"}
        self.grad_data_field = self.feed_data_field
464 465 466

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
467
        self.py_rnn = RecurrentOpNoMemBootTest.PySimpleRNN4(
468 469
            self.input_shape, self.output_shape
        )
C
chengduo 已提交
470 471

        with fluid.program_guard(self.main_program, self.startup_program):
472
            self.output = paddle.mean(self.create_rnn_op())
473 474

    def create_rnn_op(self):
G
GGBond8488 已提交
475
        x = paddle.static.data(
476 477 478 479
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
            name='x',
        )
480 481
        x.stop_gradient = False

C
chengduo 已提交
482
        rnn = layers.StaticRNN()
483 484 485
        with rnn.step():
            mem_pre = rnn.memory(shape=[-1, self.input_dim], batch_ref=x)
            x_t = rnn.step_input(x)
486
            mem = paddle.add(x=mem_pre, y=x_t)
487 488 489 490 491 492
            rnn.update_memory(mem_pre, mem)
            rnn.output(mem)

        return rnn()


493
class RecurrentOpSubBlockTest(RecurrentOpTest1):
494
    r'''
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    Test RNNOp with subblock variable
    equation:
        y_ = emb * w1
        h_t = \concat([x, h_{t-1}])
        h_t = h_t * w2
        h_t = \\unsqueeze(h_t, 1)
        h_t = \dot_attention(h_t, y_)
        h_t = \squeeze(h_t, 1)
        y = h_t
    vars:
        - x
        - w1
        - w2
    memories:
        - h
    outputs:
       - y
    '''

    class PySimpleRNN5(PyRNNBase):
        def __init__(self, input_shape, output_shape):
516
            super().__init__(input_shape, output_shape)
517 518

            seq_len, batch_size, input_dim = input_shape
519 520 521 522 523 524 525 526 527 528
            self.w1 = np.random.uniform(
                -0.1, 0.1, size=(input_dim, input_dim)
            ).astype("float32")
            self.w2 = np.random.uniform(
                -0.1, 0.1, size=(input_dim * 2, input_dim)
            ).astype("float32")

            self.emb = np.random.uniform(
                -0.1, 0.1, size=(seq_len, batch_size, input_dim)
            ).astype("float32")
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

            men_dim = (seq_len, batch_size, input_dim)
            self.mems = np.zeros(shape=men_dim).astype("float32")
            self.oy = np.matmul(self.emb, self.w1)

        def step(self, step_id, x):
            def dot_attention(query, memory):
                attn = np.matmul(query, memory.transpose((0, 2, 1)))
                weight = softmax(attn)
                weight_memory = np.matmul(weight, memory)
                return weight_memory, weight

            def softmax(x):
                return np.exp(x) / sum(np.exp(x))

            if step_id == 0:
                pre_mem = np.zeros_like(x)
            else:
                pre_mem = self.mems[step_id - 1]
            concat_in = np.concatenate([x, pre_mem], 1)
            new_mem = np.matmul(concat_in, self.w2)

            new_mem = np.expand_dims(new_mem, 1)
            new_mem, _ = dot_attention(new_mem, self.oy)
            new_mem = np.squeeze(new_mem, 1)

            self.mems[step_id] = new_mem
            self.y[step_id] = self.mems[step_id]

    input_dim = 2
    batch_size = 3
    sent_len = 3

    def setUp(self):
        self.setup_program()

565 566
        self.feed_data_field = {"x", "emb", "w1", "w2"}
        self.grad_data_field = self.feed_data_field
567 568 569

        self.input_shape = (self.sent_len, self.batch_size, self.input_dim)
        self.output_shape = (self.sent_len, self.batch_size, self.input_dim)
570
        self.py_rnn = RecurrentOpSubBlockTest.PySimpleRNN5(
571 572
            self.input_shape, self.output_shape
        )
573 574 575

        with fluid.program_guard(self.main_program, self.startup_program):
            rnn_out = self.create_rnn_op()
576
            self.output = paddle.mean(rnn_out)
577 578

    def create_rnn_op(self):
G
GGBond8488 已提交
579
        x = paddle.static.data(
580 581 582 583
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
            name='x',
        )
584 585
        x.stop_gradient = False

G
GGBond8488 已提交
586
        emb = paddle.static.data(
587 588 589
            name='emb',
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype='float32',
590
        )
591 592
        emb.stop_gradient = False

G
GGBond8488 已提交
593
        w1 = paddle.static.data(
594 595 596 597
            shape=[self.input_dim, self.input_dim],
            dtype='float32',
            name='w1',
        )
598
        w1.stop_gradient = False
G
GGBond8488 已提交
599
        w2 = paddle.static.data(
600 601 602 603
            shape=[self.input_dim * 2, self.input_dim],
            dtype='float32',
            name='w2',
        )
604 605 606 607 608
        w2.stop_gradient = False

        rnn = layers.StaticRNN()

        def dot_attention(query, memory):
K
kangguangli 已提交
609
            attn = paddle.matmul(query, memory, transpose_y=True)
610
            weight = paddle.nn.functional.softmax(attn)
K
kangguangli 已提交
611
            weight_memory = paddle.matmul(weight, memory)
612 613 614

            return weight_memory, weight

K
kangguangli 已提交
615
        y = paddle.matmul(emb, w1)
616
        with rnn.step():
617 618 619 620 621
            pre_h = rnn.memory(
                shape=(self.sent_len, self.input_dim),
                batch_ref=x,
                init_value=0.0,
            )
622 623
            step_in = rnn.step_input(x)
            concat_in = layers.concat([step_in, pre_h], 1)
K
kangguangli 已提交
624
            new_h = paddle.matmul(concat_in, w2)
625
            new_h = paddle.unsqueeze(new_h, [1])
626
            new_h, _ = dot_attention(new_h, y)
627
            new_h = paddle.squeeze(new_h, [1])
628 629 630 631 632 633 634

            rnn.update_memory(pre_h, new_h)
            rnn.step_output(new_h)

        return rnn()


635
class RecurrentOpStopGradientTest(RecurrentOpTest1):
636
    r"""
637 638 639 640 641
    Test RNNOp with stop_gradient = True
    equation:
        h_t = \sigma (W x_t + U h_{t-1})
    weights:
        - W
642
        - U
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    vars:
        - x
    memories:
        - h
    output:
        - h
    """

    input_dim = 2
    batch_size = 10
    sent_len = 2

    def setUp(self):
        self.setup_program()
        self.feed_data_field = {"x", "h_boot", "W", "U"}
        self.grad_data_field = {"x", "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)

        with fluid.program_guard(self.main_program, self.startup_program):
665
            self.output = paddle.mean(self.create_rnn_op())
666 667

    def create_rnn_op(self):
G
GGBond8488 已提交
668
        x = paddle.static.data(
669 670 671 672
            shape=[self.sent_len, self.batch_size, self.input_dim],
            dtype="float32",
            name="x",
        )
673
        x.stop_gradient = False
G
GGBond8488 已提交
674 675
        h_boot = paddle.static.data(
            shape=[-1, self.input_dim], dtype="float32", name="h_boot"
676
        )
677 678 679 680 681 682 683
        h_boot.stop_gradient = True

        rnn = layers.StaticRNN()
        with rnn.step():
            h_pre = rnn.memory(init=h_boot)  # init doesn't have gradient
            x_t = rnn.step_input(x)

C
Charles-hit 已提交
684 685
            temp_l = paddle.static.nn.fc(
                x=x_t,
686
                size=self.input_dim,
C
Charles-hit 已提交
687
                weight_attr=ParamAttr(
688
                    name="W",
689 690 691 692
                    initializer=fluid.initializer.ConstantInitializer(1.0),
                ),
                bias_attr=False,
            )
C
Charles-hit 已提交
693 694
            temp_r = paddle.static.nn.fc(
                x=h_pre,
695
                size=self.input_dim,
C
Charles-hit 已提交
696
                weight_attr=ParamAttr(
697
                    name="U",
698 699 700 701
                    initializer=fluid.initializer.ConstantInitializer(0.0),
                ),
                bias_attr=False,
            )
702

703
            h = paddle.nn.functional.sigmoid(x=paddle.add(temp_l, temp_r))
704 705 706 707 708 709 710

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

        return rnn()


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