test_conditional_block.py 1.8 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
Yu Yang 已提交
15
import unittest
16 17 18 19 20
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
21
from paddle.fluid.layers.control_flow import ConditionalBlock
Y
Yu Yang 已提交
22 23 24
import numpy


25
class ConditionalBlockTest(unittest.TestCase):
Y
Yu Yang 已提交
26
    def test_forward(self):
F
fengjiayi 已提交
27
        data = layers.data(name='X', shape=[1], dtype='float32')
Y
Yu Yang 已提交
28
        data.stop_gradient = False
29
        cond = ConditionalBlock(inputs=[data])
Y
Yu Yang 已提交
30 31 32 33 34 35 36
        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 已提交
37
        exe.run(default_startup_program())
Y
Yu Yang 已提交
38

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

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


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