test_compiled_program.py 6.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   copyright (c) 2020 paddlepaddle authors. all rights reserved.
#
# 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
#
#     http://www.apache.org/licenses/license-2.0
#
# 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.

import unittest
16

17
import numpy as np
18 19 20
from simple_nets import simple_fc_net
from test_imperative_base import new_program_scope

L
Leo Chen 已提交
21
import paddle
22 23 24 25 26 27 28 29
import paddle.fluid as fluid
from paddle.fluid import core


class TestCompiledProgram(unittest.TestCase):
    def setUp(self):
        self.seed = 100
        self.img = np.random.random(size=(16, 784)).astype('float32')
30 31 32
        self.label = np.random.randint(
            low=0, high=10, size=[16, 1], dtype=np.int64
        )
33
        with new_program_scope():
C
cnn 已提交
34
            paddle.seed(self.seed)
L
Leo Chen 已提交
35
            paddle.framework.random._manual_program_seed(self.seed)
36 37 38 39 40
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
41 42 43 44 45
            exe = fluid.Executor(place)

            loss = simple_fc_net()
            exe.run(fluid.default_startup_program())

46 47 48 49 50
            (loss_data,) = exe.run(
                fluid.default_main_program(),
                feed={"image": self.img, "label": self.label},
                fetch_list=[loss.name],
            )
51 52 53 54
            self.loss = loss_data[0]

    def test_compiled_program_base(self):
        with new_program_scope():
C
cnn 已提交
55
            paddle.seed(self.seed)
L
Leo Chen 已提交
56
            paddle.framework.random._manual_program_seed(self.seed)
57 58 59 60 61
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
62 63 64 65 66 67
            exe = fluid.Executor(place)

            loss = simple_fc_net()
            exe.run(fluid.default_startup_program())
            compiled_prog = fluid.CompiledProgram(fluid.default_main_program())

68 69 70 71 72
            (loss_data,) = exe.run(
                compiled_prog,
                feed={"image": self.img, "label": self.label},
                fetch_list=[loss.name],
            )
73
            np.testing.assert_array_equal(loss_data[0], self.loss)
74 75 76

    def test_compiled_program_with_data_parallel(self):
        with new_program_scope():
C
cnn 已提交
77
            paddle.seed(self.seed)
L
Leo Chen 已提交
78
            paddle.framework.random._manual_program_seed(self.seed)
79 80 81 82 83
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
84 85 86 87
            exe = fluid.Executor(place)

            loss = simple_fc_net()
            exe.run(fluid.default_startup_program())
88
            compiled_prog = fluid.CompiledProgram(
89 90 91 92 93 94 95 96
                fluid.default_main_program()
            ).with_data_parallel(loss_name=loss.name, places=[place])

            (loss_data,) = exe.run(
                compiled_prog,
                feed={"image": self.img, "label": self.label},
                fetch_list=[loss.name],
            )
97
            np.testing.assert_array_equal(loss_data[0], self.loss)
98 99 100 101 102 103 104


class TestCompiledProgramError(unittest.TestCase):
    def test_program_or_graph_error(self):
        self.assertRaises(TypeError, fluid.CompiledProgram, "program")

    def build_simple_model(self):
G
GGBond8488 已提交
105 106
        img = paddle.static.data(
            name='image', shape=[-1, 1, 28, 28], dtype='float32'
107
        )
G
GGBond8488 已提交
108
        label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64')
C
Charles-hit 已提交
109
        prediction = paddle.static.nn.fc(x=img, size=10, activation='softmax')
110 111 112
        loss = paddle.nn.functional.cross_entropy(
            input=prediction, label=label, reduction='none', use_softmax=False
        )
113
        avg_loss = paddle.mean(loss)
114 115 116 117 118 119 120 121

    def compile_program_not_compiled(self):
        with fluid.program_guard(fluid.Program()):
            # build model
            self.build_simple_model()
            # compile program
            program = fluid.default_main_program()
            compiled_program = fluid.CompiledProgram(
122 123
                program
            ).with_data_parallel()
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            return compiled_program

    def compile_program(self):
        with fluid.program_guard(fluid.Program()):
            # build model
            self.build_simple_model()
            # compile program
            program = fluid.default_main_program()
            compiled_program = fluid.CompiledProgram(program)
            scope = fluid.global_scope()
            place = fluid.CPUPlace()
            compiled_program._compile(scope, place)
            return compiled_program, scope, place

    def test_compile_scope_error(self):
        compiled_program, _, place = self.compile_program()
        new_scope = core.Scope()
        with self.assertRaises(ValueError):
            compiled_program._compile(new_scope, place)

    def test_compile_place_error(self):
        # need create different place
        if core.is_compiled_with_cuda():
            compiled_program, scope, _ = self.compile_program()
            new_place = fluid.CUDAPlace(0)
            with self.assertRaises(ValueError):
                compiled_program._compile(scope, new_place)

    def test_share_vars_from_error_no_parallel(self):
        with fluid.program_guard(fluid.Program()):
            source_program, _, _ = self.compile_program()
            self.build_simple_model()
            # compile program
            program = fluid.default_main_program()
            compiled_program = fluid.CompiledProgram(
159 160
                program
            ).with_data_parallel(share_vars_from=source_program)
161 162 163 164 165 166 167 168 169 170 171 172
            scope = fluid.global_scope()
            place = fluid.CPUPlace()
            with self.assertRaises(ValueError):
                compiled_program._compile(scope, place)

    def test_share_vars_from_error_no_executor(self):
        with fluid.program_guard(fluid.Program()):
            source_program = self.compile_program_not_compiled()
            self.build_simple_model()
            # compile program
            program = fluid.default_main_program()
            compiled_program = fluid.CompiledProgram(
173 174
                program
            ).with_data_parallel(share_vars_from=source_program)
175 176 177 178 179 180 181 182
            scope = fluid.global_scope()
            place = fluid.CPUPlace()
            with self.assertRaises(ValueError):
                compiled_program._compile(scope, place)


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