test_dist_fleet_ps2.py 7.4 KB
Newer Older
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.

import os
16

17 18
os.environ["WITH_DISTRIBUTE"] = "ON"

19 20
import unittest

21
import paddle
22
import paddle.fluid as fluid
23
import paddle.distributed.fleet.base.role_maker as role_maker
24
import paddle.distributed.fleet as fleet
25

P
pangyoki 已提交
26 27
paddle.enable_static()

28 29 30 31 32 33 34 35 36 37 38 39
# 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 TestPSPassWithBow(unittest.TestCase):
40

41
    def net(self):
42

43 44 45 46
        def get_acc(cos_q_nt, cos_q_pt, batch_size):
            cond = fluid.layers.less_than(cos_q_nt, cos_q_pt)
            cond = fluid.layers.cast(cond, dtype='float64')
            cond_3 = fluid.layers.reduce_sum(cond)
47 48 49 50 51 52
            acc = fluid.layers.elementwise_div(cond_3,
                                               fluid.layers.fill_constant(
                                                   shape=[1],
                                                   value=batch_size * 1.0,
                                                   dtype='float64'),
                                               name="simnet_acc")
53 54 55 56
            return acc

        def get_loss(cos_q_pt, cos_q_nt):
            loss_op1 = fluid.layers.elementwise_sub(
57 58 59 60
                fluid.layers.fill_constant_batch_size_like(input=cos_q_pt,
                                                           shape=[-1, 1],
                                                           value=margin,
                                                           dtype='float32'),
61 62 63
                cos_q_pt)
            loss_op2 = fluid.layers.elementwise_add(loss_op1, cos_q_nt)
            loss_op3 = fluid.layers.elementwise_max(
64 65 66 67
                fluid.layers.fill_constant_batch_size_like(input=loss_op2,
                                                           shape=[-1, 1],
                                                           value=0.0,
                                                           dtype='float32'),
68
                loss_op2)
69
            avg_cost = paddle.mean(loss_op3)
70 71 72 73 74 75
            return avg_cost

        is_distributed = False
        is_sparse = True

        # query
76 77 78 79
        q = fluid.layers.data(name="query_ids",
                              shape=[1],
                              dtype="int64",
                              lod_level=1)
80 81 82 83 84 85 86 87 88 89 90 91
        # 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 = fluid.layers.reshape(q_emb, [-1, emb_dim])
        # vsum
        q_sum = fluid.layers.sequence_pool(input=q_emb, pool_type='sum')
        q_ss = fluid.layers.softsign(q_sum)
92
        q_ss = fluid.layers.data_norm(input=q_ss)
93 94 95 96 97 98 99 100 101 102 103
        # fc layer after conv
        q_fc = fluid.layers.fc(
            input=q_ss,
            size=hid_dim,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__q_fc__",
                learning_rate=base_lr))
        # label data
        label = fluid.layers.data(name="label", shape=[1], dtype="int64")
        # pt
104 105 106 107
        pt = fluid.layers.data(name="pos_title_ids",
                               shape=[1],
                               dtype="int64",
                               lod_level=1)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        # 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 = fluid.layers.reshape(pt_emb, [-1, emb_dim])
        # vsum
        pt_sum = fluid.layers.sequence_pool(input=pt_emb, pool_type='sum')
        pt_ss = fluid.layers.softsign(pt_sum)
        # fc layer
        pt_fc = fluid.layers.fc(
            input=pt_ss,
            size=hid_dim,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__fc__",
                learning_rate=base_lr),
            bias_attr=fluid.ParamAttr(name="__fc_b__"))
        # nt
130 131 132 133
        nt = fluid.layers.data(name="neg_title_ids",
                               shape=[1],
                               dtype="int64",
                               lod_level=1)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        # 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 = fluid.layers.reshape(nt_emb, [-1, emb_dim])
        # vsum
        nt_sum = fluid.layers.sequence_pool(input=nt_emb, pool_type='sum')
        nt_ss = fluid.layers.softsign(nt_sum)
        # fc layer
        nt_fc = fluid.layers.fc(
            input=nt_ss,
            size=hid_dim,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.01),
                name="__fc__",
                learning_rate=base_lr),
            bias_attr=fluid.ParamAttr(name="__fc_b__"))
        cos_q_pt = fluid.layers.cos_sim(q_fc, pt_fc)
        cos_q_nt = fluid.layers.cos_sim(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):
164 165 166 167 168 169
        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"
T
tangwei12 已提交
170 171
        os.environ[
            "PADDLE_PSERVERS_IP_PORT_LIST"] = "127.0.0.1:36001,127.0.0.2:36001"
172 173 174
        os.environ["TRAINING_ROLE"] = "PSERVER"

        role = role_maker.PaddleCloudRoleMaker()
175 176
        fleet.init(role)
        loss, acc, _ = self.net()
177

178
        strategy = paddle.distributed.fleet.DistributedStrategy()
179
        strategy.a_sync = True
180 181 182

        configs = {}
        configs['__emb__'] = {
183 184 185 186
            "table_parameters.__emb__.enable_sparse_table_cache":
            True,
            "table_parameters.__emb__.shard_merge_rate":
            1,
187 188 189 190 191 192
            "table_parameters.__emb__.accessor.embed_sgd_param.name":
            "SparseNaiveSGDRule",
            "table_parameters.__emb__.accessor.embedx_sgd_param.name":
            "SparseAdamSGDRule",
        }
        strategy.sparse_table_configs = configs
M
MRXLT 已提交
193
        optimizer = paddle.fluid.optimizer.SGD(learning_rate=0.01)
194
        optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)
195 196 197 198 199 200 201
        optimizer.minimize(loss)

        fleet.init_server()


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