dist_simnet_bow.py 7.8 KB
Newer Older
T
tangwei12 已提交
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
#   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

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
from test_dist_base import TestDistRunnerBase, runtime_main

T
tangwei12 已提交
34 35
DTYPE = "int64"
DATA_URL = 'http://paddle-dist-ce-data.cdn.bcebos.com/simnet.train.1000'
T
tangwei12 已提交
36
DATA_MD5 = '4cc060b0a0939a343fc9242aa1ee2e4e'
T
tangwei12 已提交
37 38

# For Net
T
tangwei12 已提交
39
base_lr = 0.2
T
tangwei12 已提交
40 41 42 43 44 45 46 47 48 49 50 51
emb_lr = base_lr * 3
dict_dim = 1451594
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


T
tangwei12 已提交
52
def get_acc(cos_q_nt, cos_q_pt, batch_size):
T
tangwei12 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    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)
    acc = fluid.layers.elementwise_div(
        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 = fluid.layers.elementwise_sub(
        fluid.layers.fill_constant_batch_size_like(
            input=cos_q_pt, shape=[-1, 1], value=margin, dtype='float32'),
        cos_q_pt)
    loss_op2 = fluid.layers.elementwise_add(loss_op1, cos_q_nt)
    loss_op3 = fluid.layers.elementwise_max(
        fluid.layers.fill_constant_batch_size_like(
            input=loss_op2, shape=[-1, 1], value=0.0, dtype='float32'),
        loss_op2)
    avg_cost = fluid.layers.mean(loss_op3)
    return avg_cost


def get_optimizer():
    # SGD optimizer
    optimizer = fluid.optimizer.SGD(learning_rate=base_lr)
    return optimizer


T
tangwei12 已提交
84
def train_network(batch_size, is_distributed=False, is_sparse=False):
T
tangwei12 已提交
85 86 87 88 89 90
    # query
    q = fluid.layers.data(
        name="query_ids", shape=[1], dtype="int64", lod_level=1)
    ## embedding
    q_emb = fluid.layers.embedding(
        input=q,
T
tangwei12 已提交
91
        is_distributed=is_distributed,
T
tangwei12 已提交
92 93
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
T
tangwei12 已提交
94 95 96
            initializer=fluid.initializer.Constant(value=0.01),
            name="__emb__",
            learning_rate=emb_lr),
T
tangwei12 已提交
97
        is_sparse=is_sparse)
T
tangwei12 已提交
98 99 100 101
    ## vsum
    q_sum = fluid.layers.sequence_pool(input=q_emb, pool_type='sum')
    q_ss = fluid.layers.softsign(q_sum)
    ## fc layer after conv
T
tangwei12 已提交
102 103 104 105 106 107 108
    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))
T
tangwei12 已提交
109 110 111 112 113 114 115 116
    # label data
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")
    # pt
    pt = fluid.layers.data(
        name="pos_title_ids", shape=[1], dtype="int64", lod_level=1)
    ## embedding
    pt_emb = fluid.layers.embedding(
        input=pt,
T
tangwei12 已提交
117
        is_distributed=is_distributed,
T
tangwei12 已提交
118 119
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
T
tangwei12 已提交
120 121 122
            initializer=fluid.initializer.Constant(value=0.01),
            name="__emb__",
            learning_rate=emb_lr),
T
tangwei12 已提交
123
        is_sparse=is_sparse)
T
tangwei12 已提交
124 125 126 127
    ## vsum
    pt_sum = fluid.layers.sequence_pool(input=pt_emb, pool_type='sum')
    pt_ss = fluid.layers.softsign(pt_sum)
    ## fc layer
T
tangwei12 已提交
128 129 130 131 132 133 134 135
    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__"))
T
tangwei12 已提交
136 137 138 139 140 141
    # nt
    nt = fluid.layers.data(
        name="neg_title_ids", shape=[1], dtype="int64", lod_level=1)
    ## embedding
    nt_emb = fluid.layers.embedding(
        input=nt,
T
tangwei12 已提交
142
        is_distributed=is_distributed,
T
tangwei12 已提交
143 144
        size=[dict_dim, emb_dim],
        param_attr=fluid.ParamAttr(
T
tangwei12 已提交
145 146 147
            initializer=fluid.initializer.Constant(value=0.01),
            name="__emb__",
            learning_rate=emb_lr),
T
tangwei12 已提交
148
        is_sparse=is_sparse)
T
tangwei12 已提交
149 150 151 152
    ## vsum
    nt_sum = fluid.layers.sequence_pool(input=nt_emb, pool_type='sum')
    nt_ss = fluid.layers.softsign(nt_sum)
    ## fc layer
T
tangwei12 已提交
153 154 155 156 157 158 159 160
    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__"))
T
tangwei12 已提交
161 162 163 164 165
    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
T
tangwei12 已提交
166
    acc = get_acc(cos_q_nt, cos_q_pt, batch_size)
T
tangwei12 已提交
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
    return [avg_cost, acc, cos_q_pt]


def combination(x, y):
    res = [[[xi, yi] for yi in y] for xi in x]
    return res[0]


def get_one_data(file_list):
    for file in file_list:
        contents = []
        with open(file, "r") as fin:
            for i in fin:
                contents.append(i.strip())
            for index, q in enumerate(contents):
                try:
                    one_data = [[int(j) for j in i.split(" ")]
                                for i in q.split(";")[:-1]]
                    if one_data[1][0] + one_data[1][1] != len(one_data) - 3:
                        q = fin.readline()
                        continue
                    tmp = combination(one_data[3:3 + one_data[1][0]],
                                      one_data[3 + one_data[1][0]:])
                except Exception as e:
                    continue

                for each in tmp:
T
tangwei12 已提交
194
                    yield [one_data[2], 0, each[0], each[1]]
T
tangwei12 已提交
195 196


T
tangwei12 已提交
197
def get_batch_reader(file_list, batch_size):
T
tangwei12 已提交
198 199 200 201 202 203 204 205 206 207 208 209
    def batch_reader():
        res = []
        for i in get_one_data(file_list):
            if random.random() <= sample_rate:
                res.append(i)
            if len(res) >= batch_size:
                yield res
                res = []

    return batch_reader


T
tangwei12 已提交
210
def get_train_reader(batch_size):
T
tangwei12 已提交
211
    # The training data set.
T
tangwei12 已提交
212 213
    train_file = os.path.join(paddle.dataset.common.DATA_HOME, "simnet",
                              "train")
T
tangwei12 已提交
214
    train_reader = get_batch_reader([train_file], batch_size)
T
tangwei12 已提交
215 216 217 218 219 220 221
    train_feed = ["query_ids", "pos_title_ids", "neg_title_ids", "label"]
    return train_reader, train_feed


class TestDistSimnetBow2x2(TestDistRunnerBase):
    def get_model(self, batch_size=2):
        # Train program
T
tangwei12 已提交
222 223
        avg_cost, acc, predict = \
            train_network(batch_size, bool(int(os.environ["IS_DISTRIBUTED"])), bool(int(os.environ["IS_SPARSE"])))
T
tangwei12 已提交
224 225

        inference_program = fluid.default_main_program().clone()
T
tangwei12 已提交
226

T
tangwei12 已提交
227
        # Optimization
T
tangwei12 已提交
228
        opt = get_optimizer()
T
tangwei12 已提交
229 230 231
        opt.minimize(avg_cost)

        # Reader
T
tangwei12 已提交
232
        train_reader, _ = get_train_reader(batch_size)
233
        return inference_program, avg_cost, train_reader, train_reader, acc, predict
T
tangwei12 已提交
234 235 236


if __name__ == "__main__":
T
tangwei12 已提交
237 238
    paddle.dataset.common.download(DATA_URL, 'simnet', DATA_MD5, "train")

T
tangwei12 已提交
239 240
    import os
    os.environ['CPU_NUM'] = '1'
T
tangwei12 已提交
241 242 243

    os.environ["IS_DISTRIBUTED"] = '0'
    os.environ["IS_SPARSE"] = '0'
T
tangwei12 已提交
244
    runtime_main(TestDistSimnetBow2x2)
T
tangwei12 已提交
245 246 247 248

#    os.environ["IS_DISTRIBUTED"] = '0'
#    os.environ["IS_SPARSE"] = '1'
#    runtime_main(TestDistSimnetBow2x2)