test_dist_fleet_spmt.py 8.9 KB
Newer Older
L
lxsbupt 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#   Copyright (c) 2022 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.

import os
import unittest

import paddle
import paddle.fluid as fluid

paddle.enable_static()

# For Net
base_lr = 0.2
emb_lr = base_lr * 3
dict_dim = 1500
emb_dim = 128
hid_dim = 128
margin = 0.1
sample_rate = 1
batch_size = 4


class TestSPMT(unittest.TestCase):
    def net(self):
        def get_acc(cos_q_nt, cos_q_pt, batch_size):
            cond = paddle.less_than(cos_q_nt, cos_q_pt)
            cond = fluid.layers.cast(cond, dtype='float64')
            cond_3 = paddle.sum(cond)
            acc = paddle.divide(
                cond_3,
                fluid.layers.fill_constant(
                    shape=[1], value=batch_size * 1.0, dtype='float64'
                ),
                name="simnet_acc",
            )
            return acc

        def get_loss(cos_q_pt, cos_q_nt):
            loss_op1 = paddle.subtract(
                fluid.layers.fill_constant_batch_size_like(
                    input=cos_q_pt, shape=[-1, 1], value=margin, dtype='float32'
                ),
                cos_q_pt,
            )
            loss_op2 = paddle.add(loss_op1, cos_q_nt)
            loss_op3 = paddle.maximum(
                fluid.layers.fill_constant_batch_size_like(
                    input=loss_op2, shape=[-1, 1], value=0.0, dtype='float32'
                ),
                loss_op2,
            )
            avg_cost = paddle.mean(loss_op3)
            return avg_cost

        is_distributed = False
        is_sparse = True

        # query
G
GGBond8488 已提交
70 71 72
        q = paddle.static.data(
            name="1", shape=[-1, 1], dtype="int64", lod_level=1
        )
L
lxsbupt 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        # embedding
        q_emb = fluid.contrib.layers.sparse_embedding(
            input=q,
            size=[dict_dim, emb_dim],
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__emb__",
                learning_rate=emb_lr,
            ),
        )
        q_emb = paddle.reshape(q_emb, [-1, emb_dim])
        # vsum
        q_sum = fluid.layers.sequence_pool(input=q_emb, pool_type='sum')
        q_ss = paddle.nn.functional.softsign(q_sum)
        # fc layer after conv
C
Charles-hit 已提交
88 89
        q_fc = paddle.static.nn.fc(
            x=q_ss,
L
lxsbupt 已提交
90
            size=hid_dim,
C
Charles-hit 已提交
91
            weight_attr=fluid.ParamAttr(
L
lxsbupt 已提交
92 93 94 95 96 97
                initializer=fluid.initializer.Constant(value=0.01),
                name="__q_fc__",
                learning_rate=base_lr,
            ),
        )
        # label data
G
GGBond8488 已提交
98
        label = paddle.static.data(name="label", shape=[-1, 1], dtype="int64")
L
lxsbupt 已提交
99
        # pt
G
GGBond8488 已提交
100 101 102
        pt = paddle.static.data(
            name="2", shape=[-1, 1], dtype="int64", lod_level=1
        )
L
lxsbupt 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        # embedding
        pt_emb = fluid.contrib.layers.sparse_embedding(
            input=pt,
            size=[dict_dim, emb_dim],
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__emb__",
                learning_rate=emb_lr,
            ),
        )
        pt_emb = paddle.reshape(pt_emb, [-1, emb_dim])
        # vsum
        pt_sum = fluid.layers.sequence_pool(input=pt_emb, pool_type='sum')
        pt_ss = paddle.nn.functional.softsign(pt_sum)
        # fc layer
C
Charles-hit 已提交
118 119
        pt_fc = paddle.static.nn.fc(
            x=pt_ss,
L
lxsbupt 已提交
120
            size=hid_dim,
C
Charles-hit 已提交
121
            weight_attr=fluid.ParamAttr(
L
lxsbupt 已提交
122 123 124 125 126 127 128
                initializer=fluid.initializer.Constant(value=0.01),
                name="__fc__",
                learning_rate=base_lr,
            ),
            bias_attr=fluid.ParamAttr(name="__fc_b__"),
        )
        # nt
G
GGBond8488 已提交
129 130 131
        nt = paddle.static.data(
            name="3", shape=[-1, 1], dtype="int64", lod_level=1
        )
L
lxsbupt 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        # embedding
        nt_emb = fluid.contrib.layers.sparse_embedding(
            input=nt,
            size=[dict_dim, emb_dim],
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__emb__",
                learning_rate=emb_lr,
            ),
        )
        nt_emb = paddle.reshape(nt_emb, [-1, emb_dim])
        # vsum
        nt_sum = fluid.layers.sequence_pool(input=nt_emb, pool_type='sum')
        nt_ss = paddle.nn.functional.softsign(nt_sum)
        # fc layer
C
Charles-hit 已提交
147 148
        nt_fc = paddle.static.nn.fc(
            x=nt_ss,
L
lxsbupt 已提交
149
            size=hid_dim,
C
Charles-hit 已提交
150
            weight_attr=fluid.ParamAttr(
L
lxsbupt 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
                initializer=fluid.initializer.Constant(value=0.01),
                name="__fc__",
                learning_rate=base_lr,
            ),
            bias_attr=fluid.ParamAttr(name="__fc_b__"),
        )
        cos_q_pt = paddle.nn.functional.cosine_similarity(q_fc, pt_fc)
        cos_q_nt = paddle.nn.functional.cosine_similarity(q_fc, nt_fc)
        # loss
        avg_cost = get_loss(cos_q_pt, cos_q_nt)
        # acc
        acc = get_acc(cos_q_nt, cos_q_pt, batch_size)
        return [avg_cost, acc, cos_q_pt]

    # def test(self):
    #    os.environ["PADDLE_PSERVER_NUMS"] = "2"
    #    os.environ["PADDLE_TRAINERS_NUM"] = "2"
    #    os.environ["POD_IP"] = "127.0.0.1"
    #    os.environ["PADDLE_PORT"] = "36001"
    #    os.environ["PADDLE_TRAINER_ID"] = "0"
    #    os.environ["PADDLE_TRAINERS_NUM"] = "2"
    #    os.environ[
    #        "PADDLE_TRAINER_ENDPOINTS"
    #    ] = "127.0.0.1:36001,127.0.0.2:36001"
    #    os.environ[
    #        "PADDLE_PSERVERS_IP_PORT_LIST"
    #    ] = "127.0.0.1:36002,127.0.0.2:36002"
    #    os.environ["TRAINING_ROLE"] = "TRAINER"
    #    os.environ["FLAGS_selected_gpus"] = "0"
    #    role = role_maker.PaddleCloudRoleMaker()
    #    fleet.init(role)
    #    loss, acc, _ = self.net()
    #
    #    strategy = paddle.distributed.fleet.DistributedStrategy()
    #    configs = {"use_ps_gpu": 1, "launch_barrier": False}
    #    strategy.a_sync_configs = configs
    #    strategy.a_sync = True
    #    optimizer = paddle.fluid.optimizer.Adam(learning_rate=0.01)
    #    optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)
    #    optimizer.minimize(loss)

    def get_dist_env(self):
        trainer_id = int(os.getenv('PADDLE_TRAINER_ID', '0'))
        trainer_endpoints = ''
        current_endpoint = ''
        num_trainers = 0
        if os.getenv('PADDLE_TRAINER_ENDPOINTS'):
            trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS')
            current_endpoint = trainer_endpoints.split(',')[trainer_id]
            num_trainers = len(trainer_endpoints.split(','))

        return {
            'trainer_id': trainer_id,
            'num_trainers': num_trainers,
            'current_endpoint': current_endpoint,
            'trainer_endpoints': trainer_endpoints,
        }

    def test_SingleProcessMultiThread(self):
        """
        Testcase for SingleProcessMultiThread
        """
        os.environ["PADDLE_PSERVER_NUMS"] = "2"
        os.environ["PADDLE_TRAINERS_NUM"] = "2"
        os.environ["POD_IP"] = "127.0.0.1"
        os.environ["PADDLE_PORT"] = "36001"
        os.environ["PADDLE_TRAINER_ID"] = "0"
        os.environ["PADDLE_TRAINERS_NUM"] = "2"
        os.environ[
            "PADDLE_TRAINER_ENDPOINTS"
        ] = "127.0.0.1:36001,127.0.0.2:36001"
        os.environ[
            "PADDLE_PSERVERS_IP_PORT_LIST"
        ] = "127.0.0.1:36002,127.0.0.2:36002"
        os.environ["TRAINING_ROLE"] = "TRAINER"
        os.environ["FLAGS_selected_gpus"] = "0"
        os.environ["PADDLE_FUSE_ALLREDUCE"] = "1"
        os.environ["PADDLE_LOSS_SCALE"] = "1"

        startup_program = fluid.Program()
        main_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            with fluid.unique_name.guard():
                loss, acc, _ = self.net()
        optimizer = paddle.fluid.optimizer.Adam(learning_rate=0.01)
        optimizer.minimize(loss)
        print("===main_program====")
        print(main_program)
        print("===main_program====")
        from paddle.fluid.transpiler.collective import SingleProcessMultiThread

        t = SingleProcessMultiThread()
        env = self.get_dist_env()
        t.transpile(
            startup_program=startup_program,
            main_program=main_program,
            rank=env["trainer_id"],
            endpoints=env["trainer_endpoints"],
            current_endpoint=env['current_endpoint'],
            wait_port=False,
        )
        param_cnt = t._get_update_param_count()
        print("param_cnt:", param_cnt)


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