dist_mnist_gradient_merge_raw_optimizer.py 3.9 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
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 os
16 17 18 19 20 21 22 23 24 25
import paddle
import paddle.nn as nn
import paddle.fluid as fluid
import paddle.distributed.fleet as fleet
import numpy as np
from test_dist_base import TestDistRunnerBase, runtime_main
from dist_mnist import cnn_model


class TestDistMnistGradientMergeRawOptimizer(TestDistRunnerBase):
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    def get_model(self, batch_size=2, single_device=False):
        paddle.enable_static()
        paddle.seed(1)
        np.random.seed(1)

        assert fluid.core.globals()['FLAGS_apply_pass_to_program']
        strategy = fleet.DistributedStrategy()
        build_strategy = paddle.static.BuildStrategy()
        settings = {
            "fuse_relu_depthwise_conv": True,
            "fuse_bn_act_ops": True,
            "fuse_bn_add_act_ops": True,
            "fuse_elewise_add_act_ops": True,
            "fuse_all_optimizer_ops": True,
            "enable_addto": True,
            "enable_inplace": True,
        }
        for k, v in settings.items():
            setattr(build_strategy, k, v)
        strategy.build_strategy = build_strategy

        strategy.gradient_merge = True
49
        avg = os.environ['enable_gm_avg'] == "True"
50 51
        strategy.gradient_merge_configs = {
            "k_steps": 2,
52
            "avg": avg,
53 54 55 56
        }
        strategy.without_graph_optimization = True

        fleet.init(is_collective=True, strategy=strategy)
57 58 59
        image = paddle.static.data(name='image',
                                   shape=[None, 1, 28, 28],
                                   dtype="float32")
60 61 62 63 64 65 66 67 68 69 70 71
        label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        predict = cnn_model(image)
        acc = paddle.metric.accuracy(predict, label)
        loss_fn = nn.CrossEntropyLoss(use_softmax=False)
        cost = loss_fn(predict, label)
        test_program = paddle.static.default_main_program().clone(for_test=True)
        optimizer = paddle.optimizer.Adam(learning_rate=1e-3)
        if single_device:
            optimizer = fluid.optimizer.GradientMergeOptimizer(
                optimizer,
                k_steps=strategy.gradient_merge_configs["k_steps"],
                avg=strategy.gradient_merge_configs["avg"])
72
            world_size = 1
73 74
        else:
            optimizer = fleet.distributed_optimizer(optimizer)
75
            world_size = fleet.world_size()
76
        optimizer.minimize(cost)
77 78 79 80 81 82 83 84 85 86 87 88 89 90
        if world_size > 1:
            assert paddle.static.default_main_program().num_blocks == 2
            gm_block = paddle.static.default_main_program().block(1)
            start_allreduce_idx = None
            for i, op in enumerate(gm_block.ops):
                if op.type == "c_allreduce_sum":
                    start_allreduce_idx = i
                    break
            # the magic number 1 below means skip the c_sync_calc_stream op
            if avg:
                assert start_allreduce_idx > 1
            else:
                assert start_allreduce_idx == 1

91 92 93 94
        train_reader = paddle.batch(paddle.dataset.mnist.test(),
                                    batch_size=batch_size)
        test_reader = paddle.batch(paddle.dataset.mnist.test(),
                                   batch_size=batch_size)
95 96 97 98 99
        return test_program, cost, train_reader, test_reader, acc, predict


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