test_print_op.py 5.2 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
Yan Chunwei 已提交
17
import unittest
18 19
import paddle.fluid.core as core
from paddle.fluid.executor import Executor
20
import paddle.fluid as fluid
21 22 23 24
import paddle.fluid.layers as layers
from paddle.fluid.backward import append_backward
from paddle.fluid.framework import switch_main_program
from paddle.fluid.framework import Program
Y
yangyaming 已提交
25
import numpy as np
26
from simple_nets import simple_fc_net, init_data
27 28
from paddle.fluid import compiler, Program, program_guard
from op_test import OpTest
Y
yangyaming 已提交
29 30 31 32 33 34 35 36


class TestPrintOpCPU(unittest.TestCase):
    def setUp(self):
        self.place = core.CPUPlace()
        self.x_tensor = core.LoDTensor()
        tensor_np = np.random.random(size=(2, 3)).astype('float32')
        self.x_tensor.set(tensor_np, self.place)
37
        self.x_tensor.set_recursive_sequence_lengths([[1, 1]])
Y
Yan Chunwei 已提交
38

Y
yangyaming 已提交
39 40 41
    def build_network(self, only_forward, **kargs):
        x = layers.data('x', shape=[3], dtype='float32', lod_level=1)
        x.stop_gradient = False
Y
Yu Yang 已提交
42 43
        layers.Print(input=x, **kargs)
        loss = layers.mean(x)
Y
yangyaming 已提交
44 45
        append_backward(loss=loss)
        return loss
Y
Yan Chunwei 已提交
46

Y
yangyaming 已提交
47 48 49 50 51 52 53
    def test_forward(self):
        switch_main_program(Program())
        printed = self.build_network(True, print_phase='forward')
        exe = Executor(self.place)
        outs = exe.run(feed={'x': self.x_tensor},
                       fetch_list=[printed],
                       return_numpy=False)
Y
Yan Chunwei 已提交
54

Y
yangyaming 已提交
55 56 57 58 59 60 61
    def test_backward(self):
        switch_main_program(Program())
        loss = self.build_network(False, print_phase='backward')
        exe = Executor(self.place)
        outs = exe.run(feed={'x': self.x_tensor},
                       fetch_list=[loss],
                       return_numpy=False)
Y
Yan Chunwei 已提交
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    def test_all_parameters(self):
        x = layers.data('x', shape=[3], dtype='float32', lod_level=1)
        x.stop_gradient = False

        for print_tensor_name in [True, False]:
            for print_tensor_type in [True, False]:
                for print_tensor_shape in [True, False]:
                    for print_tensor_lod in [True, False]:
                        layers.Print(
                            input=x,
                            print_tensor_name=print_tensor_name,
                            print_tensor_type=print_tensor_type,
                            print_tensor_shape=print_tensor_shape,
                            print_tensor_lod=print_tensor_lod, )
        loss = layers.mean(x)
        append_backward(loss=loss)
        exe = Executor(self.place)
        outs = exe.run(feed={'x': self.x_tensor},
                       fetch_list=[loss],
                       return_numpy=False)

Y
Yan Chunwei 已提交
84

85 86 87 88 89 90 91 92 93 94 95 96
class TestPrintOpError(OpTest):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of Print_op must be Variable.
            x1 = fluid.create_lod_tensor(
                np.array([[-1]]), [[1]], fluid.CPUPlace())
            self.assertRaises(TypeError, fluid.layers.Print, x1)
            # The input dtype of Print_op must be float32, float64, int32_t, int64_t or bool.
            x2 = fluid.layers.data(name='x2', shape=[4], dtype="float16")
            self.assertRaises(TypeError, fluid.layers.Print, x2)


97 98
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
Y
yangyaming 已提交
99 100 101 102 103 104
class TestPrintOpGPU(TestPrintOpCPU):
    def setUp(self):
        self.place = core.CUDAPlace(0)
        self.x_tensor = core.LoDTensor()
        tensor_np = np.random.random(size=(2, 3)).astype('float32')
        self.x_tensor.set(tensor_np, self.place)
105
        self.x_tensor.set_recursive_sequence_lengths([[1, 1]])
Y
Yan Chunwei 已提交
106 107


108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
class TestPrintOpBackward(unittest.TestCase):
    def check_backward(self, use_cuda):
        main = fluid.Program()
        startup = fluid.Program()

        with fluid.program_guard(main, startup):
            loss = simple_fc_net()
            loss = fluid.layers.Print(loss)
            fluid.optimizer.Adam().minimize(loss)

        print_ops = [op for op in main.blocks[0].ops if op.type == u'print']
        assert len(print_ops) == 2, "The number of print op should be 2"

        place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(startup)

        binary = fluid.compiler.CompiledProgram(main).with_data_parallel(
            loss_name=loss.name)

        img, label = init_data()
        feed_dict = {"image": img, "label": label}
        exe.run(binary, feed_dict)

    def test_fw_bw(self):
        if core.is_compiled_with_cuda():
            self.check_backward(use_cuda=True)
        self.check_backward(use_cuda=False)


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