dist_fleet_simnet_bow.py 8.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   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.

from __future__ import print_function

import numpy as np
import argparse
import time
import math
import random
22 23
import shutil
import tempfile
24 25 26 27 28 29 30 31 32 33

import paddle
import paddle.fluid as fluid
import paddle.fluid.profiler as profiler
from paddle.fluid import core
import unittest
from multiprocessing import Process
import os
import signal
from functools import reduce
34
from test_dist_fleet_base import runtime_main, FleetDistRunnerBase
35

P
pangyoki 已提交
36 37
paddle.enable_static()

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
DTYPE = "int64"
DATA_URL = 'http://paddle-dist-ce-data.bj.bcebos.com/simnet.train.1000'
DATA_MD5 = '24e49366eb0611c552667989de2f57d5'

# 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

# Fix seed for test
fluid.default_startup_program().random_seed = 1
fluid.default_main_program().random_seed = 1


56
def fake_simnet_reader():
57

58 59 60 61 62 63 64 65 66 67 68
    def reader():
        for _ in range(1000):
            q = np.random.random_integers(0, 1500 - 1, size=1).tolist()
            label = np.random.random_integers(0, 1, size=1).tolist()
            pt = np.random.random_integers(0, 1500 - 1, size=1).tolist()
            nt = np.random.random_integers(0, 1500 - 1, size=1).tolist()
            yield [q, label, pt, nt]

    return reader


69 70 71 72
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)
73 74 75 76 77 78
    acc = fluid.layers.elementwise_div(cond_3,
                                       fluid.layers.fill_constant(
                                           shape=[1],
                                           value=batch_size * 1.0,
                                           dtype='float64'),
                                       name="simnet_acc")
79 80 81 82 83
    return acc


def get_loss(cos_q_pt, cos_q_nt):
    loss_op1 = fluid.layers.elementwise_sub(
84 85 86 87
        fluid.layers.fill_constant_batch_size_like(input=cos_q_pt,
                                                   shape=[-1, 1],
                                                   value=margin,
                                                   dtype='float32'), cos_q_pt)
88 89
    loss_op2 = fluid.layers.elementwise_add(loss_op1, cos_q_nt)
    loss_op3 = fluid.layers.elementwise_max(
90 91 92 93
        fluid.layers.fill_constant_batch_size_like(input=loss_op2,
                                                   shape=[-1, 1],
                                                   value=0.0,
                                                   dtype='float32'), loss_op2)
94 95 96 97
    avg_cost = fluid.layers.mean(loss_op3)
    return avg_cost


98 99 100
def train_network(batch_size,
                  is_distributed=False,
                  is_sparse=False,
101 102
                  is_self_contained_lr=False,
                  is_pyreader=False):
103
    # query
104 105 106 107
    q = fluid.layers.data(name="query_ids",
                          shape=[1],
                          dtype="int64",
                          lod_level=1)
108 109 110
    # label data
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")
    # pt
111 112 113 114
    pt = fluid.layers.data(name="pos_title_ids",
                           shape=[1],
                           dtype="int64",
                           lod_level=1)
115
    # nt
116 117 118 119
    nt = fluid.layers.data(name="neg_title_ids",
                           shape=[1],
                           dtype="int64",
                           lod_level=1)
120 121 122 123 124

    datas = [q, label, pt, nt]

    reader = None
    if is_pyreader:
125 126 127 128
        reader = fluid.io.PyReader(feed_list=datas,
                                   capacity=64,
                                   iterable=False,
                                   use_double_buffer=False)
129

130 131
    # embedding
    q_emb = fluid.embedding(
132 133 134 135
        input=q,
        is_distributed=is_distributed,
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
136
            initializer=fluid.initializer.Constant(value=0.01), name="__emb__"),
137
        is_sparse=is_sparse)
138 139
    q_emb = fluid.layers.reshape(q_emb, [-1, emb_dim])
    # vsum
140 141
    q_sum = fluid.layers.sequence_pool(input=q_emb, pool_type='sum')
    q_ss = fluid.layers.softsign(q_sum)
142
    # fc layer after conv
143 144 145 146 147 148
    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__",
149 150
            learning_rate=base_lr),
    )
151

152 153
    # embedding
    pt_emb = fluid.embedding(
154 155 156 157 158 159
        input=pt,
        is_distributed=is_distributed,
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
            initializer=fluid.initializer.Constant(value=0.01),
            name="__emb__",
160
            learning_rate=emb_lr),
161
        is_sparse=is_sparse)
162 163
    pt_emb = fluid.layers.reshape(pt_emb, [-1, emb_dim])
    # vsum
164 165
    pt_sum = fluid.layers.sequence_pool(input=pt_emb, pool_type='sum')
    pt_ss = fluid.layers.softsign(pt_sum)
166
    # fc layer
167 168 169 170
    pt_fc = fluid.layers.fc(
        input=pt_ss,
        size=hid_dim,
        param_attr=fluid.ParamAttr(
171
            initializer=fluid.initializer.Constant(value=0.01), name="__fc__"),
172
        bias_attr=fluid.ParamAttr(name="__fc_b__"))
173

174 175
    # embedding
    nt_emb = fluid.embedding(
176 177 178 179
        input=nt,
        is_distributed=is_distributed,
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
180
            initializer=fluid.initializer.Constant(value=0.01), name="__emb__"),
181
        is_sparse=is_sparse)
182 183
    nt_emb = fluid.layers.reshape(nt_emb, [-1, emb_dim])
    # vsum
184 185
    nt_sum = fluid.layers.sequence_pool(input=nt_emb, pool_type='sum')
    nt_ss = fluid.layers.softsign(nt_sum)
186
    # fc layer
187 188 189 190
    nt_fc = fluid.layers.fc(
        input=nt_ss,
        size=hid_dim,
        param_attr=fluid.ParamAttr(
191
            initializer=fluid.initializer.Constant(value=0.01), name="__fc__"),
192 193 194 195 196 197 198
        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)
199 200 201 202 203 204 205 206 207 208 209
    return avg_cost, acc, cos_q_pt, reader


class TestDistSimnetBow2x2(FleetDistRunnerBase):
    """
    For test SimnetBow model, use Fleet api
    """

    def net(self, args, batch_size=4, lr=0.01):
        avg_cost, _, predict, self.reader = \
            train_network(batch_size=batch_size, is_distributed=False,
210
                          is_sparse=True, is_self_contained_lr=False, is_pyreader=(args.reader == "pyreader"))
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        self.avg_cost = avg_cost
        self.predict = predict

        return avg_cost

    def check_model_right(self, dirname):
        model_filename = os.path.join(dirname, "__model__")

        with open(model_filename, "rb") as f:
            program_desc_str = f.read()

        program = fluid.Program.parse_from_string(program_desc_str)
        with open(os.path.join(dirname, "__model__.proto"), "w") as wn:
            wn.write(str(program))

    def do_pyreader_training(self, fleet):
        """
        do training using dataset, using fetch handler to catch variable
        Args:
            fleet(Fleet api): the fleet object of Parameter Server, define distribute training role
        """

        exe = fluid.Executor(fluid.CPUPlace())
        exe.run(fluid.default_startup_program())
T
tangwei12 已提交
235
        fleet.init_worker()
236 237 238 239 240 241 242 243 244 245 246 247
        batch_size = 4
        # reader
        train_reader = paddle.batch(fake_simnet_reader(), batch_size=batch_size)
        self.reader.decorate_sample_list_generator(train_reader)
        for epoch_id in range(1):
            self.reader.start()
            try:
                pass_start = time.time()
                while True:
                    loss_val = exe.run(program=fluid.default_main_program(),
                                       fetch_list=[self.avg_cost.name])
                    loss_val = np.mean(loss_val)
248 249
                    message = "TRAIN ---> pass: {} loss: {}\n".format(
                        epoch_id, loss_val)
250
                    fleet.util.print_on_rank(message, 0)
251 252 253 254 255 256 257

                pass_time = time.time() - pass_start
            except fluid.core.EOFException:
                self.reader.reset()

    def do_dataset_training(self, fleet):
        pass
258 259 260 261


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