dist_allreduce_op.py 3.9 KB
Newer Older
W
Wu Yi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2018 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 functools import reduce
16

L
LoneRanger 已提交
17
import nets
W
Wu Yi 已提交
18 19
from test_dist_base import TestDistRunnerBase, runtime_main

20
import paddle
21 22
from paddle import fluid
from paddle.distributed import fleet
23

P
pangyoki 已提交
24 25
paddle.enable_static()

W
Wu Yi 已提交
26 27 28 29 30 31 32 33 34
DTYPE = "float32"
paddle.dataset.mnist.fetch()

# Fix seed for test
fluid.default_startup_program().random_seed = 1
fluid.default_main_program().random_seed = 1


def cnn_model(data):
L
LoneRanger 已提交
35
    conv_pool_1 = nets.simple_img_conv_pool(
W
Wu Yi 已提交
36 37 38 39 40 41
        input=data,
        filter_size=5,
        num_filters=20,
        pool_size=2,
        pool_stride=2,
        act="relu",
42
        param_attr=fluid.ParamAttr(
43
            initializer=paddle.nn.initializer.Constant(value=0.01)
44 45
        ),
    )
L
LoneRanger 已提交
46
    conv_pool_2 = nets.simple_img_conv_pool(
W
Wu Yi 已提交
47 48 49 50 51 52
        input=conv_pool_1,
        filter_size=5,
        num_filters=50,
        pool_size=2,
        pool_stride=2,
        act="relu",
53
        param_attr=fluid.ParamAttr(
54
            initializer=paddle.nn.initializer.Constant(value=0.01)
55 56
        ),
    )
W
Wu Yi 已提交
57 58 59 60

    SIZE = 10
    input_shape = conv_pool_2.shape
    param_shape = [reduce(lambda a, b: a * b, input_shape[1:], 1)] + [SIZE]
61
    scale = (2.0 / (param_shape[0] ** 2 * SIZE)) ** 0.5
W
Wu Yi 已提交
62

C
Charles-hit 已提交
63 64
    predict = paddle.static.nn.fc(
        x=conv_pool_2,
W
Wu Yi 已提交
65
        size=SIZE,
C
Charles-hit 已提交
66 67
        activation="softmax",
        weight_attr=fluid.param_attr.ParamAttr(
68
            initializer=paddle.nn.initializer.Constant(value=0.01)
69 70
        ),
    )
W
Wu Yi 已提交
71 72 73 74 75 76
    return predict


class TestDistMnist2x2(TestDistRunnerBase):
    def get_model(self, batch_size=2, single_device=False):
        # Input data
G
GGBond8488 已提交
77 78 79 80
        images = paddle.static.data(
            name='pixel', shape=[-1, 1, 28, 28], dtype=DTYPE
        )
        label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64')
W
Wu Yi 已提交
81 82 83

        # Train program
        predict = cnn_model(images)
84 85 86
        cost = paddle.nn.functional.cross_entropy(
            input=predict, label=label, reduction='none', use_softmax=False
        )
87
        avg_cost = paddle.mean(x=cost)
W
Wu Yi 已提交
88 89

        # Evaluator
90
        batch_size_tensor = paddle.tensor.create_tensor(dtype='int64')
91
        batch_acc = paddle.static.accuracy(
92 93
            input=predict, label=label, total=batch_size_tensor
        )
W
Wu Yi 已提交
94 95 96 97

        inference_program = fluid.default_main_program().clone()

        # Reader
98 99 100 101 102 103
        train_reader = paddle.batch(
            paddle.dataset.mnist.test(), batch_size=batch_size
        )
        test_reader = paddle.batch(
            paddle.dataset.mnist.test(), batch_size=batch_size
        )
W
Wu Yi 已提交
104 105 106 107 108 109 110 111 112 113

        # Optimization
        # TODO(typhoonzero): fix distributed adam optimizer
        # opt = fluid.optimizer.AdamOptimizer(
        #     learning_rate=0.001, beta1=0.9, beta2=0.999)
        opt = fluid.optimizer.Momentum(learning_rate=self.lr, momentum=0.9)
        if single_device:
            opt.minimize(avg_cost)
        else:
            # multi device or distributed multi device
114 115 116 117 118
            strategy = fleet.DistributedStrategy()
            strategy.without_graph_optimization = True
            fleet.init(strategy=strategy)
            optimizer = fleet.distributed_optimizer(opt)
            optimizer.minimize(avg_cost)
W
Wu Yi 已提交
119

120 121 122 123 124 125 126 127
        return (
            inference_program,
            avg_cost,
            train_reader,
            test_reader,
            batch_acc,
            predict,
        )
W
Wu Yi 已提交
128 129 130 131


if __name__ == "__main__":
    runtime_main(TestDistMnist2x2)