test_program.py 10.7 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
from paddle.fluid.framework import Program, default_main_program, program_guard
18
import paddle
19
import paddle.fluid.layers as layers
20
import paddle.fluid as fluid
Y
Yu Yang 已提交
21

22 23
paddle.enable_static()

Y
Yu Yang 已提交
24 25
main_program = default_main_program()

Y
Yu Yang 已提交
26 27 28

class TestProgram(unittest.TestCase):
    def test_program(self):
Y
Yu Yang 已提交
29
        b = main_program.current_block()
Y
Yu Yang 已提交
30 31 32
        self.assertEqual(-1, b.parent_idx)
        self.assertEqual(0, b.idx)

W
Wu Yi 已提交
33
        b = main_program._create_block()
Y
Yu Yang 已提交
34 35 36
        self.assertEqual(1, b.idx)
        self.assertEqual(0, b.parent_idx)

W
Wu Yi 已提交
37
        b = main_program._create_block()
Y
Yu Yang 已提交
38 39 40
        self.assertEqual(2, b.idx)
        self.assertEqual(1, b.parent_idx)

W
Wu Yi 已提交
41
        main_program._rollback()
Y
Yu Yang 已提交
42

Y
Yu Yang 已提交
43
        b = main_program.current_block()
Y
Yu Yang 已提交
44 45 46
        self.assertEqual(1, b.idx)
        self.assertEqual(0, b.parent_idx)

W
Wu Yi 已提交
47
        b = main_program._create_block()
Y
Yu Yang 已提交
48 49 50
        self.assertEqual(3, b.idx)
        self.assertEqual(1, b.parent_idx)

W
Wu Yi 已提交
51
        main_program._rollback()
Y
Yu Yang 已提交
52
        b = main_program.current_block()
Y
Yu Yang 已提交
53 54 55
        self.assertEqual(1, b.idx)
        self.assertEqual(0, b.parent_idx)

Y
Yu Yang 已提交
56 57 58
    def test_program_clone(self):
        prog = Program()

59 60 61
        x = prog.global_block().create_var(
            name='X', shape=[1000, 784], dtype='float32'
        )
Y
Yu Yang 已提交
62

63 64 65
        y = prog.global_block().create_var(
            name='Y', shape=[784, 100], dtype='float32'
        )
Y
Yu Yang 已提交
66
        out = prog.global_block().create_var(name='Out', dtype='float32')
67 68 69
        prog.global_block().append_op(
            type="mul", inputs={'X': [x], 'Y': [y]}, outputs={'Out': [out]}
        )
Y
Yu Yang 已提交
70 71 72

        # FIXME(yuyang18): We manual compare the output string, since the order
        # of variable could be changed.
73 74
        print(prog)
        print(prog.clone())
Y
Yu Yang 已提交
75

76 77 78
    def test_parse_program_from_string(self):
        prog = Program()

79 80 81
        x = prog.global_block().create_var(
            name='X', shape=[1000, 784], dtype='float32'
        )
82

83 84 85
        y = prog.global_block().create_var(
            name='Y', shape=[784, 100], dtype='float32'
        )
86
        out = prog.global_block().create_var(name='Out', dtype='float32')
87 88 89
        prog.global_block().append_op(
            type="mul", inputs={'X': [x], 'Y': [y]}, outputs={'Out': [out]}
        )
90 91 92 93

        binary_str = prog.desc.serialize_to_string()
        prog_restored = Program.parse_from_string(binary_str)

94 95
        print(prog)
        print(prog_restored)
96

97 98 99
    def test_program_clone_with_parameter(self):
        main_program = Program()
        startup_program = Program()
100 101 102 103
        with program_guard(main_program, startup_program):
            d = layers.data(name='x', shape=[784], dtype='float32')
            hidden = layers.fc(input=d, size=100)
            layers.fc(input=hidden, size=100)
104 105 106 107

        new_program = main_program.clone()
        self.assertNotEqual(0, len(new_program.blocks[0].all_parameters()))

108 109
    def test_program_inference_optimize(self):
        def net():
110 111 112 113 114 115 116
            reader = fluid.layers.py_reader(
                capacity=10,
                shapes=[[-1, 10], [-1, 1]],
                lod_levels=[0, 0],
                dtypes=['float32', 'int64'],
                use_double_buffer=True,
            )
117 118
            in_data, label = fluid.layers.read_file(reader)
            predict_label = fluid.layers.fc(in_data, size=2, act='softmax')
119
            loss = paddle.mean(
120 121
                fluid.layers.cross_entropy(input=predict_label, label=label)
            )
122 123 124 125 126 127 128 129

            optimizer = fluid.optimizer.Adam()
            optimizer.minimize(loss)

        startup_program = fluid.Program()
        main_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            net()
W
Wu Yi 已提交
130 131
        no_read_program = main_program._inference_optimize()
        keep_read_program = main_program._inference_optimize(
132 133
            prune_read_op=False
        )
134 135 136 137 138 139 140 141 142
        no_read_ops = no_read_program.global_block().ops
        keep_read_ops = keep_read_program.global_block().ops
        self.assertEqual(len(keep_read_ops) - len(no_read_ops), 2)
        self.assertEqual(keep_read_ops[0].type, 'create_double_buffer_reader')
        self.assertEqual(keep_read_ops[1].type, 'read')

        for i in range(len(no_read_ops)):
            self.assertEqual(no_read_ops[i].type, keep_read_ops[i + 2].type)

143 144 145 146
    def test_program_all_parameters(self):
        program = fluid.default_main_program()
        data = fluid.data(name='x', shape=[None, 13], dtype='float32')
        hidden = fluid.layers.fc(input=data, size=10)
147
        loss = paddle.mean(hidden)
148 149 150 151 152 153 154 155
        fluid.optimizer.SGD(learning_rate=0.01).minimize(loss)

        # NOTE: here the parameters are fc_0.w_0 and fc_0.b_0
        param_list = program.all_parameters()
        self.assertEqual(len(param_list), 2)
        self.assertEqual(param_list[0].name, "fc_0.w_0")
        self.assertEqual(param_list[1].name, "fc_0.b_0")

156 157 158
    def test_prune_with_input_type_error(self):
        program = fluid.default_main_program()
        feed_var_names = [2, 3, 4]
159 160 161
        self.assertRaises(
            ValueError, program._prune_with_input, feed_var_names, []
        )
162 163 164 165 166 167 168 169 170

    def test_random_seed_error(self):
        program = fluid.default_main_program()
        with self.assertRaises(ValueError):
            program.random_seed = "seed"

    def test_copy_info_from_error(self):
        program = fluid.default_main_program()
        self.assertRaises(TypeError, program._copy_param_info_from, "program")
171 172 173
        self.assertRaises(
            TypeError, program._copy_dist_param_info_from, "program"
        )
174

175 176
    def test_remove_training_info(self):
        def net():
177 178 179 180 181 182 183
            reader = fluid.layers.py_reader(
                capacity=10,
                shapes=[[-1, 10], [-1, 1]],
                lod_levels=[0, 0],
                dtypes=['float32', 'int64'],
                use_double_buffer=True,
            )
184 185
            in_data, label = fluid.layers.read_file(reader)
            predict_label = fluid.layers.fc(in_data, size=2, act='softmax')
186
            loss = paddle.mean(
187 188
                fluid.layers.cross_entropy(input=predict_label, label=label)
            )
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

            optimizer = fluid.optimizer.Adam()
            optimizer.minimize(loss)

        main_program = fluid.Program()
        with fluid.program_guard(main_program):
            net()

        removed_program = main_program._remove_training_info()

        for i in range(removed_program.num_blocks):
            block = removed_program.block(i)
            for var in block.desc.all_vars():
                self.assertFalse(var.has_is_parameter())
                self.assertFalse(var.has_stop_gradient())

Y
Yu Yang 已提交
205

L
Leo Chen 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
def build_program():
    main_program = paddle.static.Program()
    startuo_program = paddle.static.Program()
    with paddle.utils.unique_name.guard():
        with paddle.static.program_guard(main_program, startuo_program):
            x = paddle.static.data(name='x', shape=[3, 2, 1])
            out = paddle.static.nn.fc(x=x, size=1, num_flatten_dims=2)
    return main_program


class TestProgramProto(unittest.TestCase):
    def test_update_op(self):
        program = build_program()
        a = program.desc.serialize_to_string()
        program.current_block().ops[0]._set_attr('use_mkldnn', True)
        self.assertTrue(program.desc.need_update())
        b = program.desc.serialize_to_string()
        self.assertFalse(a == b)

    def test_update_var(self):
        program = build_program()
        a = program.desc.serialize_to_string()
        program.current_block().var("x").desc.set_stop_gradient(False)
        self.assertTrue(program.desc.need_update())
        b = program.desc.serialize_to_string()
        self.assertFalse(a == b)

    def test_update_var_attr(self):
        program = build_program()
        a = program.desc.serialize_to_string()
        program.current_block().var("x").desc._set_attr("a", 1)
237
        self.assertTrue(program.desc.need_update())
L
Leo Chen 已提交
238
        b = program.desc.serialize_to_string()
239
        self.assertFalse(a == b)
L
Leo Chen 已提交
240 241


L
Leo Chen 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
class TestProgramHash(unittest.TestCase):
    def build_program(self):
        main_program = paddle.static.Program()
        startuo_program = paddle.static.Program()
        with paddle.utils.unique_name.guard():
            with paddle.static.program_guard(main_program, startuo_program):
                x = paddle.static.data(name='x', shape=[3, 2, 1])
                out = paddle.static.nn.fc(x=x, size=1, num_flatten_dims=2)
        return main_program

    def test_program_need_update(self):
        program = self.build_program()
        self.assertTrue(program.desc.need_update())
        program.desc.flush()
        self.assertFalse(program.desc.need_update())

    def test_program_hash_equal(self):
        programs = []
        for i in range(2):
            programs.append(self.build_program())
        program1, program2 = programs[0], programs[1]
        # why not write as below?
        # since the callstack attribute are not equal
265 266
        # program1 = self.build_program()
        # program2 = self.build_program()
L
Leo Chen 已提交
267 268 269 270 271 272 273

        self.assertTrue(program1.desc.need_update())
        self.assertTrue(program2.desc.need_update())
        # two program with same content
        self.assertFalse(id(program1) == id(program2))
        # print(program1, program2)
        self.assertTrue(
274 275
            program1.desc.cached_hash_str() == program2.desc.cached_hash_str()
        )
L
Leo Chen 已提交
276 277 278 279 280 281 282 283 284

        self.assertFalse(program1.desc.need_update())
        self.assertFalse(program2.desc.need_update())

    def test_program_clone(self):
        program = self.build_program()
        program_clone = program.clone()

        self.assertFalse(id(program) == id(program_clone))
285 286 287 288
        self.assertTrue(
            program.desc.cached_hash_str()
            == program_clone.desc.cached_hash_str()
        )
L
Leo Chen 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302

    def test_program_update(self):
        program = self.build_program()
        hash1 = program.desc.cached_hash_str()
        id1 = id(program)
        # change mul's attr
        program.current_block().ops[0]._set_attr('use_mkldnn', True)
        program.current_block().ops[0]._set_attr('scale_x', 2.0)
        hash2 = program.desc.cached_hash_str()
        id2 = id(program)
        self.assertTrue(id1 == id2)
        self.assertFalse(hash1 == hash2)


Y
Yu Yang 已提交
303 304
if __name__ == '__main__':
    unittest.main()