test_communicator_geo.py 5.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15
import os
16
import subprocess
17
import sys
18
import time
19
import unittest
20

21
import numpy
22

23
import paddle
24
import paddle.distributed.fleet as fleet
25 26
import paddle.distributed.fleet.base.role_maker as role_maker
import paddle.fluid as fluid
R
Roc 已提交
27
from paddle.distributed.utils.launch_utils import find_free_ports
T
tangwei12 已提交
28

P
pangyoki 已提交
29 30
paddle.enable_static()

31

32
class TestCommunicatorGeoEnd2End(unittest.TestCase):
33
    def net(self):
G
GGBond8488 已提交
34 35 36 37
        x = paddle.static.data(name='x', shape=[-1, 13], dtype='float32')
        x1 = paddle.static.data(
            name='x1', shape=[-1, 1], dtype='int64', lod_level=1
        )
38 39 40 41 42 43

        emb = fluid.layers.embedding(
            input=x1,
            size=[10000, 10],
            param_attr=fluid.ParamAttr(
                name="embedding",
44
                initializer=paddle.nn.initializer.Constant(value=0.01),
45 46 47
            ),
            is_sparse=True,
        )
48

49 50 51
        pool = paddle.static.nn.sequence_lod.sequence_pool(
            input=emb, pool_type="sum"
        )
52
        z = fluid.layers.concat(input=[x, pool], axis=1)
C
Charles-hit 已提交
53
        y_predict = paddle.static.nn.fc(x=z, size=1)
G
GGBond8488 已提交
54
        y = paddle.static.data(name='y', shape=[-1, 1], dtype='float32')
55
        cost = paddle.nn.functional.square_error_cost(input=y_predict, label=y)
56
        avg_cost = paddle.mean(cost)
57
        return avg_cost, x, x1, y
58

59 60 61 62
    def fake_reader(self):
        def reader():
            for i in range(10000):
                x = numpy.random.random((1, 13)).astype('float32')
63
                z = numpy.random.randint(0, 9999, (1, 1)).astype('int64')
64
                y = numpy.random.randint(0, 2, (1, 1)).astype('int64')
65
                yield x, z, y
66

67
        return reader
68

69 70
    def run_pserver(self, role, strategy):
        fleet.init(role)
71
        avg_cost, x, z, y = self.net()
72
        optimizer = fluid.optimizer.SGD(0.01)
73 74
        optimizer = fleet.distributed_optimizer(optimizer, strategy)
        optimizer.minimize(avg_cost)
75

76 77 78 79 80 81 82 83
        fleet.init_server()
        fleet.run_server()

    def run_trainer(self, role, strategy):
        place = fluid.core.CPUPlace()
        exe = fluid.Executor(place)

        fleet.init(role)
84
        avg_cost, x, z, y = self.net()
85
        optimizer = fluid.optimizer.SGD(0.01)
86 87 88
        optimizer = fleet.distributed_optimizer(optimizer, strategy)
        optimizer.minimize(avg_cost)

89
        exe.run(fluid.default_startup_program())
T
tangwei12 已提交
90
        fleet.init_worker()
91 92

        train_reader = paddle.batch(self.fake_reader(), batch_size=24)
93
        feeder = fluid.DataFeeder(place=place, feed_list=[x, z, y])
94 95

        for batch_id, data in enumerate(train_reader()):
96 97 98 99 100
            exe.run(
                fluid.default_main_program(),
                feed=feeder.feed(data),
                fetch_list=[],
            )
101

102
        fleet.stop_worker()
103

104 105 106
    def run_ut(self):
        training_role = os.getenv("TRAINING_ROLE", "TRAINER")

107 108 109 110
        os.environ["PADDLE_PSERVER_NUMS"] = "1"
        os.environ["PADDLE_TRAINERS_NUM"] = "1"
        os.environ["PADDLE_TRAINER_ID"] = "0"
        os.environ["PADDLE_TRAINERS_NUM"] = "1"
T
tangwei12 已提交
111
        os.environ["POD_IP"] = "127.0.0.1"
112

113 114
        role = role_maker.PaddleCloudRoleMaker()

115
        strategy = paddle.distributed.fleet.DistributedStrategy()
116 117
        strategy.a_sync = True
        strategy.a_sync_configs = {"k_steps": 100}
C
Chengmo 已提交
118
        strategy.a_sync_configs = {"launch_barrier": False}
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

        if training_role == "TRAINER":
            self.run_trainer(role, strategy)
        else:
            self.run_pserver(role, strategy)

    def test_communicator(self):
        run_server_cmd = """

import sys
import os

import time
import threading
import subprocess
import unittest
import numpy

import paddle
import paddle.fluid as fluid

W
wangxiaoning 已提交
140
from paddle.distributed.communicator import Communicator
141 142
import paddle.fluid.incubate.fleet.base.role_maker as role_maker
from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode
143
import paddle.distributed.fleet as fleet
144 145 146

from test_communicator_geo import TestCommunicatorGeoEnd2End

P
pangyoki 已提交
147
paddle.enable_static()
148 149 150 151 152 153 154 155 156 157 158 159 160 161

class RunServer(TestCommunicatorGeoEnd2End):
    def runTest(self):
        pass

os.environ["TRAINING_ROLE"] = "PSERVER"

half_run_server = RunServer()
half_run_server.run_ut()
"""

        server_file = "run_server_for_communicator_geo.py"
        with open(server_file, "w") as wb:
            wb.write(run_server_cmd)
T
tangwei12 已提交
162 163 164

        port = find_free_ports(1).pop()

165
        os.environ["TRAINING_ROLE"] = "PSERVER"
T
tangwei12 已提交
166 167
        os.environ["PADDLE_PORT"] = str(port)
        os.environ["PADDLE_PSERVERS_IP_PORT_LIST"] = "127.0.0.1:{}".format(port)
168 169 170 171

        _python = sys.executable

        ps_cmd = "{} {}".format(_python, server_file)
T
tangwei12 已提交
172

173 174 175 176 177
        ps_proc = subprocess.Popen(
            ps_cmd.strip().split(" "),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
178

T
tangwei12 已提交
179
        time.sleep(5)
180

181
        os.environ["TRAINING_ROLE"] = "TRAINER"
182

183 184
        self.run_ut()
        ps_proc.kill()
T
tangwei12 已提交
185
        ps_proc.wait()
T
tangwei12 已提交
186
        outs, errs = ps_proc.communicate()
187

188 189
        if os.path.exists(server_file):
            os.remove(server_file)
190

191 192 193

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