test_graph_wrapper.py 6.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   copyright (c) 2019 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.

from __future__ import print_function
import unittest
import paddle.fluid as fluid
import six
import numpy as np
from paddle.fluid.contrib.slim.graph import GraphWrapper
from paddle.fluid import core
C
chengduo 已提交
22 23
import os
os.environ['CPU_NUM'] = str(4)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90


def residual_block(num):
    def conv_bn_layer(input,
                      ch_out,
                      filter_size,
                      stride,
                      padding,
                      act='relu',
                      bias_attr=False):
        tmp = fluid.layers.conv2d(
            input=input,
            filter_size=filter_size,
            num_filters=ch_out,
            stride=stride,
            padding=padding,
            act=None,
            bias_attr=bias_attr)
        return fluid.layers.batch_norm(input=tmp, act=act)

    data = fluid.layers.data(name='image', shape=[1, 8, 8], dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')
    data.stop_gradinet = False
    hidden = data
    for _ in six.moves.xrange(num):
        conv = conv_bn_layer(hidden, 16, 3, 1, 1, act=None, bias_attr=True)
        short = conv_bn_layer(hidden, 16, 1, 1, 0, act=None)
        hidden = fluid.layers.elementwise_add(x=conv, y=short, act='relu')
    fc = fluid.layers.fc(input=hidden, size=10)

    loss = fluid.layers.cross_entropy(input=fc, label=label)
    loss = fluid.layers.mean(loss)
    return data, label, loss


class TestGraphWrapper(unittest.TestCase):
    def build_program(self):
        place = fluid.CPUPlace()
        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
        main = fluid.Program()
        startup = fluid.Program()
        with fluid.program_guard(main, startup):
            image, label, self.loss = residual_block(2)
            eval_program = main.clone()
            opt = fluid.optimizer.SGD(learning_rate=0.001)
            opt.minimize(self.loss)
        self.scope = core.Scope()
        exe = fluid.Executor(place)
        exe.run(startup, scope=self.scope)
        self.eval_graph = GraphWrapper(
            program=eval_program,
            in_nodes={'image': image.name,
                      'label': label.name},
            out_nodes={'loss': self.loss.name})
        self.train_graph = GraphWrapper(
            program=main,
            in_nodes={'image': image.name,
                      'label': label.name},
            out_nodes={'loss': self.loss.name})

    def test_all_parameters(self):
        self.build_program()
        self.assertEquals(len(self.train_graph.all_parameters()), 24)

    def test_all_vars(self):
        self.build_program()
L
liuwei1031 已提交
91 92 93 94
        # self.assertEquals(len(self.train_graph.vars()), 90)
        # activation inplace has been disabled in python side
        # which may produce more variable in program_desc
        # update 90 => 94
95 96 97
        # delete three useless RAW variables in Conv2D
        # update 94 => 91
        self.assertEquals(len(self.train_graph.vars()), 91)
98 99 100 101 102 103 104 105 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 138 139 140 141

    def test_numel_params(self):
        self.build_program()
        self.assertEquals(self.train_graph.numel_params(), 13258)

    def test_compile(self):
        self.build_program()
        place = fluid.CPUPlace()
        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
        exe = fluid.Executor(place)
        self.train_graph.compile()
        exe.run(self.train_graph.compiled_graph,
                scope=self.scope,
                feed={
                    'image':
                    np.random.randint(0, 40, [16, 1, 8, 8]).astype('float32'),
                    'label': np.random.randint(0, 10, [16, 1]).astype('int64')
                })

    def test_pre_and_next_ops(self):
        self.build_program()
        for op in self.train_graph.ops():
            for next_op in self.train_graph.next_ops(op):
                self.assertTrue(op in self.train_graph.pre_ops(next_op))

    def test_get_optimize_graph(self):
        self.build_program()
        place = fluid.CPUPlace()
        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
        opt = fluid.optimizer.SGD(learning_rate=0.001)
        train_graph = self.eval_graph.get_optimize_graph(
            opt, place, self.scope, no_grad_var_names=['image'])
        self.assertEquals(len(self.train_graph.ops()), len(train_graph.ops()))
        exe = fluid.Executor(place)
        train_graph.compile()
        image = np.random.randint(0, 225, [16, 1, 8, 8]).astype('float32')
        label = np.random.randint(0, 10, [16, 1]).astype('int64')
        exe.run(train_graph.compiled_graph,
                scope=self.scope,
                feed={'image': image,
                      'label': label})

142 143 144 145 146 147 148 149 150 151 152
    def test_get_optimize_graph_without_loss(self):
        self.build_program()
        self.eval_graph.out_nodes = {}
        place = fluid.CPUPlace()
        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
        opt = fluid.optimizer.SGD(learning_rate=0.001)
        train_graph = self.eval_graph.get_optimize_graph(
            opt, place, self.scope, no_grad_var_names=['image'])
        self.assertEquals(train_graph, None)

153 154 155 156
    def test_flops(self):
        self.build_program()
        self.assertEquals(self.train_graph.flops(), 354624)

157 158 159 160 161
    def test_merge(self):
        self.build_program()
        self.train_graph.merge(self.eval_graph)
        self.assertEquals(len(self.train_graph.ops()), 72)

162 163 164

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