test_conditional_block.py 1.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

Y
Yu Yang 已提交
17
import unittest
18 19 20 21 22
import paddle.fluid.layers as layers
import paddle.fluid.core as core
from paddle.fluid.framework import default_startup_program, default_main_program
from paddle.fluid.executor import Executor
from paddle.fluid.backward import append_backward
23
from paddle.fluid.layers.control_flow import ConditionalBlock
Y
Yu Yang 已提交
24 25 26
import numpy


27
class ConditionalBlockTest(unittest.TestCase):
Y
Yu Yang 已提交
28
    def test_forward(self):
F
fengjiayi 已提交
29
        data = layers.data(name='X', shape=[1], dtype='float32')
Y
Yu Yang 已提交
30
        data.stop_gradient = False
31
        cond = ConditionalBlock(inputs=[data])
Y
Yu Yang 已提交
32 33 34 35 36 37 38
        out = layers.create_tensor(dtype='float32')
        with cond.block():
            hidden = layers.fc(input=data, size=10)
            layers.assign(hidden, out)

        cpu = core.CPUPlace()
        exe = Executor(cpu)
Y
Yu Yang 已提交
39
        exe.run(default_startup_program())
Y
Yu Yang 已提交
40

D
dzhwinter 已提交
41
        x = numpy.random.random(size=(10, 1)).astype('float32')
Y
Yu Yang 已提交
42

D
dzhwinter 已提交
43
        outs = exe.run(feed={'X': x}, fetch_list=[out])[0]
44
        print(outs)
Y
Yu Yang 已提交
45
        loss = layers.mean(out)
F
fengjiayi 已提交
46
        append_backward(loss=loss)
D
dzhwinter 已提交
47 48
        outs = exe.run(
            feed={'X': x},
Y
Yu Yang 已提交
49 50 51
            fetch_list=[
                default_main_program().block(0).var(data.name + "@GRAD")
            ])[0]
52
        print(outs)
Y
Yu Yang 已提交
53 54 55 56


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