test_fleet.py 4.2 KB
Newer Older
X
xujiaqi01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   Copyright (c) 2020 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.
"""Test fleet."""

import os
import unittest


class TestFleet1(unittest.TestCase):
    """
X
xujiaqi01 已提交
22 23
    Test cases for fleet minimize,
    and some other fleet apu tests.
X
xujiaqi01 已提交
24 25 26 27 28 29
    """

    def setUp(self):
        """Set up, set envs."""
        os.environ["PADDLE_TRAINERS_NUM"] = "2"
        os.environ[
30 31
            "PADDLE_PSERVERS_IP_PORT_LIST"
        ] = "127.0.0.1:36001,127.0.0.2:36001"
X
xujiaqi01 已提交
32 33 34

    def test_pslib_1(self):
        """Test cases for pslib."""
35
        import paddle
X
xujiaqi01 已提交
36 37
        import paddle.fluid as fluid
        from paddle.fluid.incubate.fleet.base.role_maker import GeneralRoleMaker
38
        from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
1
123malin 已提交
39

X
xujiaqi01 已提交
40 41 42 43 44 45 46
        os.environ["POD_IP"] = "127.0.0.1"
        os.environ["PADDLE_PORT"] = "36001"
        os.environ["TRAINING_ROLE"] = "TRAINER"
        os.environ["PADDLE_TRAINER_ENDPOINTS"] = "127.0.0.1:36001"
        os.environ["PADDLE_PSERVERS_IP_PORT_LIST"] = "127.0.0.1:36002"
        os.environ["PADDLE_TRAINER_ID"] = "0"
        role_maker = GeneralRoleMaker()
47
        # role_maker.generate_role()
X
xujiaqi01 已提交
48 49
        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
50
        # fleet.init(role_maker)
X
xujiaqi01 已提交
51 52 53 54
        train_program = fluid.Program()
        startup_program = fluid.Program()
        scope = fluid.Scope()
        with fluid.program_guard(train_program, startup_program):
55 56 57 58 59 60 61 62 63 64 65 66 67 68
            show = fluid.layers.data(
                name="show",
                shape=[-1, 1],
                dtype="int64",
                lod_level=1,
                append_batch_size=False,
            )
            emb = fluid.layers.embedding(
                input=show,
                size=[1, 1],
                is_sparse=True,
                is_distributed=True,
                param_attr=fluid.ParamAttr(name="embedding"),
            )
X
xujiaqi01 已提交
69
            bow = fluid.layers.sequence_pool(input=emb, pool_type='sum')
70 71 72
            bow = paddle.static.nn.data_norm(
                input=bow, epsilon=1e-4, name="norm"
            )
C
Charles-hit 已提交
73
            fc = paddle.static.nn.fc(x=bow, size=1, activation=None)
74 75 76 77 78 79 80
            label = fluid.layers.data(
                name="click",
                shape=[-1, 1],
                dtype="int64",
                lod_level=1,
                append_batch_size=False,
            )
X
xujiaqi01 已提交
81
            label_cast = fluid.layers.cast(label, dtype='float32')
82
            cost = paddle.nn.functional.log_loss(fc, label_cast)
X
xujiaqi01 已提交
83 84 85 86 87 88 89 90
        try:
            adam = fluid.optimizer.Adam(learning_rate=0.000005)
            adam = fleet.distributed_optimizer(
                adam,
                strategy={
                    "embedding": {
                        "sparse_accessor_class": "DownpourSparseValueAccessor"
                    }
91 92
                },
            )
X
xujiaqi01 已提交
93 94 95 96 97
            adam.minimize([cost], [scope])
            fleet.run_server()
        except:
            print("do not support pslib test, skip")
            return
X
xujiaqi01 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        try:
            # worker should call these methods instead of server
            # the following is only for test when with_pslib=off
            def test_func():
                """
                it is only a test function
                """
                return True

            fleet._role_maker.is_first_worker = test_func
            fleet._role_maker._barrier_worker = test_func
            fleet.save_model("./model_000")
            fleet.save_one_table(0, "./model_001")
            fleet.save_one_table(0, "./model_002", prefix="hahaha")
            fleet.load_model("./model_0003")
            fleet.load_one_table(0, "./model_004")
        except:
            print("do not support pslib test, skip")
            return
X
xujiaqi01 已提交
117 118 119 120


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