test_image_classification.py 10.4 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
import contextlib
16
import math
武毅 已提交
17
import os
18
import sys
19
import tempfile
20 21 22 23
import unittest

import numpy

L
LoneRanger 已提交
24 25 26 27
# TODO: remove sys.path.append
sys.path.append("../legacy_test")
import nets

28
import paddle
29
from paddle import fluid
Q
Qiao Longfei 已提交
30

P
pangyoki 已提交
31 32
paddle.enable_static()

Q
Qiao Longfei 已提交
33

34
def resnet_cifar10(input, depth=32):
35 36 37
    def conv_bn_layer(
        input, ch_out, filter_size, stride, padding, act='relu', bias_attr=False
    ):
38
        tmp = paddle.static.nn.conv2d(
39 40 41 42 43 44 45 46
            input=input,
            filter_size=filter_size,
            num_filters=ch_out,
            stride=stride,
            padding=padding,
            act=None,
            bias_attr=bias_attr,
        )
47
        return paddle.static.nn.batch_norm(input=tmp, act=act)
Q
Qiao Longfei 已提交
48

49
    def shortcut(input, ch_in, ch_out, stride):
Q
Qiao Longfei 已提交
50
        if ch_in != ch_out:
51
            return conv_bn_layer(input, ch_out, 1, stride, 0, None)
Q
Qiao Longfei 已提交
52 53 54
        else:
            return input

Q
Qiao Longfei 已提交
55 56
    def basicblock(input, ch_in, ch_out, stride):
        tmp = conv_bn_layer(input, ch_out, 3, stride, 1)
57
        tmp = conv_bn_layer(tmp, ch_out, 3, 1, 1, act=None, bias_attr=True)
58
        short = shortcut(input, ch_in, ch_out, stride)
59
        return paddle.nn.functional.relu(paddle.add(x=tmp, y=short))
Q
Qiao Longfei 已提交
60

61 62
    def layer_warp(block_func, input, ch_in, ch_out, count, stride):
        tmp = block_func(input, ch_in, ch_out, stride)
Q
Qiao Longfei 已提交
63
        for i in range(1, count):
64
            tmp = block_func(tmp, ch_out, ch_out, 1)
Q
Qiao Longfei 已提交
65 66 67
        return tmp

    assert (depth - 2) % 6 == 0
M
minqiyang 已提交
68
    n = (depth - 2) // 6
69 70 71
    conv1 = conv_bn_layer(
        input=input, ch_out=16, filter_size=3, stride=1, padding=1
    )
Q
Qiao Longfei 已提交
72 73 74
    res1 = layer_warp(basicblock, conv1, 16, 16, n, 1)
    res2 = layer_warp(basicblock, res1, 16, 32, n, 2)
    res3 = layer_warp(basicblock, res2, 32, 64, n, 2)
C
ccrrong 已提交
75
    pool = paddle.nn.functional.avg_pool2d(x=res3, kernel_size=8, stride=1)
Q
Qiao Longfei 已提交
76 77 78
    return pool


79
def vgg16_bn_drop(input):
Q
Qiao Longfei 已提交
80
    def conv_block(input, num_filter, groups, dropouts):
L
LoneRanger 已提交
81
        return nets.img_conv_group(
82 83 84 85 86 87 88 89 90 91
            input=input,
            pool_size=2,
            pool_stride=2,
            conv_num_filter=[num_filter] * groups,
            conv_filter_size=3,
            conv_act='relu',
            conv_with_batchnorm=True,
            conv_batchnorm_drop_rate=dropouts,
            pool_type='max',
        )
Q
Qiao Longfei 已提交
92

93 94 95 96 97
    conv1 = conv_block(input, 64, 2, [0.3, 0])
    conv2 = conv_block(conv1, 128, 2, [0.4, 0])
    conv3 = conv_block(conv2, 256, 3, [0.4, 0.4, 0])
    conv4 = conv_block(conv3, 512, 3, [0.4, 0.4, 0])
    conv5 = conv_block(conv4, 512, 3, [0.4, 0.4, 0])
Q
Qiao Longfei 已提交
98

C
ccrrong 已提交
99
    drop = paddle.nn.functional.dropout(x=conv5, p=0.5)
C
Charles-hit 已提交
100
    fc1 = paddle.static.nn.fc(x=drop, size=4096)
101
    bn = paddle.static.nn.batch_norm(input=fc1, act='relu')
C
ccrrong 已提交
102
    drop2 = paddle.nn.functional.dropout(x=bn, p=0.5)
C
Charles-hit 已提交
103
    fc2 = paddle.static.nn.fc(x=drop2, size=4096)
Q
Qiao Longfei 已提交
104 105 106
    return fc2


武毅 已提交
107
def train(net_type, use_cuda, save_dirname, is_local):
108 109 110
    classdim = 10
    data_shape = [3, 32, 32]

G
GGBond8488 已提交
111 112 113 114
    images = paddle.static.data(
        name='pixel', shape=[-1] + data_shape, dtype='float32'
    )
    label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64')
115 116 117 118 119 120 121 122 123 124

    if net_type == "vgg":
        print("train vgg net")
        net = vgg16_bn_drop(images)
    elif net_type == "resnet":
        print("train resnet")
        net = resnet_cifar10(images, 32)
    else:
        raise ValueError("%s network is not supported" % net_type)

C
Charles-hit 已提交
125
    predict = paddle.static.nn.fc(x=net, size=classdim, activation='softmax')
126 127 128
    cost = paddle.nn.functional.cross_entropy(
        input=predict, label=label, reduction='none', use_softmax=False
    )
129
    avg_cost = paddle.mean(cost)
130
    acc = paddle.static.accuracy(input=predict, label=label)
131

132
    # Test program
133
    test_program = fluid.default_main_program().clone(for_test=True)
134 135

    optimizer = fluid.optimizer.Adam(learning_rate=0.001)
W
Wu Yi 已提交
136
    optimizer.minimize(avg_cost)
137 138 139 140

    BATCH_SIZE = 128
    PASS_NUM = 1

141 142 143 144 145 146
    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.cifar.train10(), buf_size=128 * 10
        ),
        batch_size=BATCH_SIZE,
    )
147

148 149 150
    test_reader = paddle.batch(
        paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE
    )
151

152 153 154
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)
    feeder = fluid.DataFeeder(place=place, feed_list=[images, label])
武毅 已提交
155 156 157 158 159 160 161 162 163 164 165 166

    def train_loop(main_program):
        exe.run(fluid.default_startup_program())
        loss = 0.0
        for pass_id in range(PASS_NUM):
            for batch_id, data in enumerate(train_reader()):
                exe.run(main_program, feed=feeder.feed(data))

                if (batch_id % 10) == 0:
                    acc_list = []
                    avg_loss_list = []
                    for tid, test_data in enumerate(test_reader()):
167 168 169 170 171
                        loss_t, acc_t = exe.run(
                            program=test_program,
                            feed=feeder.feed(test_data),
                            fetch_list=[avg_cost, acc],
                        )
武毅 已提交
172 173 174 175 176 177 178 179 180
                        if math.isnan(float(loss_t)):
                            sys.exit("got NaN loss, training failed.")
                        acc_list.append(float(acc_t))
                        avg_loss_list.append(float(loss_t))
                        break  # Use 1 segment for speeding up CI

                    acc_value = numpy.array(acc_list).mean()
                    avg_loss_value = numpy.array(avg_loss_list).mean()

181
                    print(
182
                        'PassID {:1}, BatchID {:04}, Test Loss {:2.2}, Acc {:2.2}'.format(
183 184 185 186 187 188
                            pass_id,
                            batch_id + 1,
                            float(avg_loss_value),
                            float(acc_value),
                        )
                    )
武毅 已提交
189 190

                    if acc_value > 0.01:  # Low threshold for speeding up CI
191 192 193
                        fluid.io.save_inference_model(
                            save_dirname, ["pixel"], [predict], exe
                        )
武毅 已提交
194 195 196 197 198
                        return

    if is_local:
        train_loop(fluid.default_main_program())
    else:
G
gongweibao 已提交
199 200
        port = os.getenv("PADDLE_PSERVER_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_PSERVER_IPS")  # ip,ip...
武毅 已提交
201 202 203 204
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
G
gongweibao 已提交
205
        trainers = int(os.getenv("PADDLE_TRAINERS"))
武毅 已提交
206
        current_endpoint = os.getenv("POD_IP") + ":" + port
G
gongweibao 已提交
207 208
        trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
        training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
209
        t = paddle.distributed.transpiler.DistributeTranspiler()
Y
Yancey1989 已提交
210
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
武毅 已提交
211 212
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
213 214 215
            pserver_startup = t.get_startup_program(
                current_endpoint, pserver_prog
            )
武毅 已提交
216 217 218 219
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())
220 221 222 223 224 225 226 227 228


def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

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

229 230 231
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
T
tianshuo78520a 已提交
232
        # the feed_target_names (the names of variables that will be fed
233 234
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
235 236 237 238 239
        [
            inference_program,
            feed_target_names,
            fetch_targets,
        ] = fluid.io.load_inference_model(save_dirname, exe)
240 241 242 243 244 245 246 247

        # The input's dimension of conv should be 4-D or 5-D.
        # Use normilized image pixels as input data, which should be in the range [0, 1.0].
        batch_size = 1
        tensor_img = numpy.random.rand(batch_size, 3, 32, 32).astype("float32")

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
248 249 250 251 252
        results = exe.run(
            inference_program,
            feed={feed_target_names[0]: tensor_img},
            fetch_list=fetch_targets,
        )
253

254
        print("infer results: ", results[0])
255

256 257 258 259 260 261 262
        fluid.io.save_inference_model(
            save_dirname,
            feed_target_names,
            fetch_targets,
            exe,
            inference_program,
        )
263

264

武毅 已提交
265
def main(net_type, use_cuda, is_local=True):
266 267 268 269
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the trained model
270 271
    temp_dir = tempfile.TemporaryDirectory()
    save_dirname = os.path.join(
272 273
        temp_dir.name, "image_classification_" + net_type + ".inference.model"
    )
274

武毅 已提交
275
    train(net_type, use_cuda, save_dirname, is_local)
276
    infer(use_cuda, save_dirname)
277
    temp_dir.cleanup()
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308


class TestImageClassification(unittest.TestCase):
    def test_vgg_cuda(self):
        with self.scope_prog_guard():
            main('vgg', use_cuda=True)

    def test_resnet_cuda(self):
        with self.scope_prog_guard():
            main('resnet', use_cuda=True)

    def test_vgg_cpu(self):
        with self.scope_prog_guard():
            main('vgg', use_cuda=False)

    def test_resnet_cpu(self):
        with self.scope_prog_guard():
            main('resnet', use_cuda=False)

    @contextlib.contextmanager
    def scope_prog_guard(self):
        prog = fluid.Program()
        startup_prog = fluid.Program()
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
            with fluid.program_guard(prog, startup_prog):
                yield


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