test_recommender_system.py 12.5 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15
import math
武毅 已提交
16
import os
17 18 19
import sys
import tempfile

Q
Qiao Longfei 已提交
20
import numpy as np
21

22
import paddle
23 24 25 26 27 28
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.fluid.layers as layers
import paddle.fluid.nets as nets
from paddle.fluid.executor import Executor
from paddle.fluid.optimizer import SGDOptimizer
29

P
pangyoki 已提交
30 31
paddle.enable_static()

32 33
IS_SPARSE = True
USE_GPU = False
34 35 36 37 38 39 40 41 42
BATCH_SIZE = 256


def get_usr_combined_features():
    # FIXME(dzh) : old API integer_value(10) may has range check.
    # currently we don't have user configurated check.

    USR_DICT_SIZE = paddle.dataset.movielens.max_user_id() + 1

G
GGBond8488 已提交
43
    uid = paddle.static.data(name='user_id', shape=[-1, 1], dtype='int64')
44

45 46 47 48 49 50 51
    usr_emb = layers.embedding(
        input=uid,
        dtype='float32',
        size=[USR_DICT_SIZE, 32],
        param_attr='user_table',
        is_sparse=IS_SPARSE,
    )
52

C
Charles-hit 已提交
53
    usr_fc = paddle.static.nn.fc(x=usr_emb, size=32)
54 55 56

    USR_GENDER_DICT_SIZE = 2

G
GGBond8488 已提交
57 58 59
    usr_gender_id = paddle.static.data(
        name='gender_id', shape=[-1, 1], dtype='int64'
    )
60

61 62 63 64 65 66
    usr_gender_emb = layers.embedding(
        input=usr_gender_id,
        size=[USR_GENDER_DICT_SIZE, 16],
        param_attr='gender_table',
        is_sparse=IS_SPARSE,
    )
67

C
Charles-hit 已提交
68
    usr_gender_fc = paddle.static.nn.fc(x=usr_gender_emb, size=16)
69 70

    USR_AGE_DICT_SIZE = len(paddle.dataset.movielens.age_table)
G
GGBond8488 已提交
71
    usr_age_id = paddle.static.data(name='age_id', shape=[-1, 1], dtype="int64")
72

73 74 75 76 77 78
    usr_age_emb = layers.embedding(
        input=usr_age_id,
        size=[USR_AGE_DICT_SIZE, 16],
        is_sparse=IS_SPARSE,
        param_attr='age_table',
    )
79

C
Charles-hit 已提交
80
    usr_age_fc = paddle.static.nn.fc(x=usr_age_emb, size=16)
81 82

    USR_JOB_DICT_SIZE = paddle.dataset.movielens.max_job_id() + 1
G
GGBond8488 已提交
83
    usr_job_id = paddle.static.data(name='job_id', shape=[-1, 1], dtype="int64")
84

85 86 87 88 89 90
    usr_job_emb = layers.embedding(
        input=usr_job_id,
        size=[USR_JOB_DICT_SIZE, 16],
        param_attr='job_table',
        is_sparse=IS_SPARSE,
    )
91

C
Charles-hit 已提交
92
    usr_job_fc = paddle.static.nn.fc(x=usr_job_emb, size=16)
93 94

    concat_embed = layers.concat(
95 96
        input=[usr_fc, usr_gender_fc, usr_age_fc, usr_job_fc], axis=1
    )
97

C
Charles-hit 已提交
98 99 100
    usr_combined_features = paddle.static.nn.fc(
        x=concat_embed, size=200, activation="tanh"
    )
101 102 103 104 105 106 107 108

    return usr_combined_features


def get_mov_combined_features():

    MOV_DICT_SIZE = paddle.dataset.movielens.max_movie_id() + 1

G
GGBond8488 已提交
109
    mov_id = paddle.static.data(name='movie_id', shape=[-1, 1], dtype='int64')
110

111 112 113 114 115 116 117
    mov_emb = layers.embedding(
        input=mov_id,
        dtype='float32',
        size=[MOV_DICT_SIZE, 32],
        param_attr='movie_table',
        is_sparse=IS_SPARSE,
    )
118

C
Charles-hit 已提交
119
    mov_fc = paddle.static.nn.fc(x=mov_emb, size=32)
120 121 122

    CATEGORY_DICT_SIZE = len(paddle.dataset.movielens.movie_categories())

G
GGBond8488 已提交
123 124
    category_id = paddle.static.data(
        name='category_id', shape=[-1, 1], dtype='int64', lod_level=1
125
    )
126

127 128 129
    mov_categories_emb = layers.embedding(
        input=category_id, size=[CATEGORY_DICT_SIZE, 32], is_sparse=IS_SPARSE
    )
130

131 132 133
    mov_categories_hidden = layers.sequence_pool(
        input=mov_categories_emb, pool_type="sum"
    )
134 135 136

    MOV_TITLE_DICT_SIZE = len(paddle.dataset.movielens.get_movie_title_dict())

G
GGBond8488 已提交
137 138
    mov_title_id = paddle.static.data(
        name='movie_title', shape=[-1, 1], dtype='int64', lod_level=1
139
    )
140

141 142 143
    mov_title_emb = layers.embedding(
        input=mov_title_id, size=[MOV_TITLE_DICT_SIZE, 32], is_sparse=IS_SPARSE
    )
144

145 146 147 148 149 150 151
    mov_title_conv = nets.sequence_conv_pool(
        input=mov_title_emb,
        num_filters=32,
        filter_size=3,
        act="tanh",
        pool_type="sum",
    )
152 153

    concat_embed = layers.concat(
154 155
        input=[mov_fc, mov_categories_hidden, mov_title_conv], axis=1
    )
156 157

    # FIXME(dzh) : need tanh operator
C
Charles-hit 已提交
158 159 160
    mov_combined_features = paddle.static.nn.fc(
        x=concat_embed, size=200, activation="tanh"
    )
161 162 163 164 165 166 167 168 169

    return mov_combined_features


def model():
    usr_combined_features = get_usr_combined_features()
    mov_combined_features = get_mov_combined_features()

    # need cos sim
C
ccrrong 已提交
170 171 172
    inference = paddle.nn.functional.cosine_similarity(
        x1=usr_combined_features, x2=mov_combined_features
    )
2
201716010711 已提交
173
    scale_infer = paddle.scale(x=inference, scale=5.0)
174

G
GGBond8488 已提交
175
    label = paddle.static.data(name='score', shape=[-1, 1], dtype='float32')
176 177 178
    square_cost = paddle.nn.functional.square_error_cost(
        input=scale_infer, label=label
    )
179
    avg_cost = paddle.mean(square_cost)
180

181 182
    return scale_infer, avg_cost

183

武毅 已提交
184
def train(use_cuda, save_dirname, is_local=True):
185 186 187
    scale_infer, avg_cost = model()

    # test program
188
    test_program = fluid.default_main_program().clone(for_test=True)
189

Q
Qiao Longfei 已提交
190
    sgd_optimizer = SGDOptimizer(learning_rate=0.2)
W
Wu Yi 已提交
191
    sgd_optimizer.minimize(avg_cost)
192

193
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
194 195 196

    exe = Executor(place)

197 198 199 200 201 202 203
    train_reader = paddle.batch(
        paddle.reader.shuffle(paddle.dataset.movielens.train(), buf_size=8192),
        batch_size=BATCH_SIZE,
    )
    test_reader = paddle.batch(
        paddle.dataset.movielens.test(), batch_size=BATCH_SIZE
    )
204

205
    feed_order = [
206 207 208 209 210 211 212 213
        'user_id',
        'gender_id',
        'age_id',
        'job_id',
        'movie_id',
        'category_id',
        'movie_title',
        'score',
214
    ]
215

武毅 已提交
216 217 218
    def train_loop(main_program):
        exe.run(framework.default_startup_program())

219 220 221 222 223
        feed_list = [
            main_program.global_block().var(var_name) for var_name in feed_order
        ]
        feeder = fluid.DataFeeder(feed_list, place)

武毅 已提交
224 225 226 227
        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for batch_id, data in enumerate(train_reader()):
                # train a mini-batch
228 229 230 231 232
                outs = exe.run(
                    program=main_program,
                    feed=feeder.feed(data),
                    fetch_list=[avg_cost],
                )
武毅 已提交
233 234 235 236
                out = np.array(outs[0])
                if (batch_id + 1) % 10 == 0:
                    avg_cost_set = []
                    for test_data in test_reader():
237 238 239 240 241
                        avg_cost_np = exe.run(
                            program=test_program,
                            feed=feeder.feed(test_data),
                            fetch_list=[avg_cost],
                        )
武毅 已提交
242 243 244 245 246 247 248 249
                        avg_cost_set.append(avg_cost_np[0])
                        break  # test only 1 segment for speeding up CI

                    # get test avg_cost
                    test_avg_cost = np.array(avg_cost_set).mean()
                    if test_avg_cost < 6.0:
                        # if avg_cost less than 6.0, we think our code is good.
                        if save_dirname is not None:
250
                            fluid.io.save_inference_model(
251 252 253 254 255 256 257 258 259 260 261 262 263
                                save_dirname,
                                [
                                    "user_id",
                                    "gender_id",
                                    "age_id",
                                    "job_id",
                                    "movie_id",
                                    "category_id",
                                    "movie_title",
                                ],
                                [scale_infer],
                                exe,
                            )
武毅 已提交
264 265 266 267 268 269 270 271
                        return

                if math.isnan(float(out[0])):
                    sys.exit("got NaN loss, training failed.")

    if is_local:
        train_loop(fluid.default_main_program())
    else:
G
gongweibao 已提交
272 273
        port = os.getenv("PADDLE_PSERVER_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_PSERVER_IPS")  # ip,ip...
武毅 已提交
274 275 276 277
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
G
gongweibao 已提交
278
        trainers = int(os.getenv("PADDLE_TRAINERS"))
武毅 已提交
279
        current_endpoint = os.getenv("POD_IP") + ":" + port
G
gongweibao 已提交
280 281
        trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
        training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
武毅 已提交
282
        t = fluid.DistributeTranspiler()
Y
Yancey1989 已提交
283
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
武毅 已提交
284 285
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
286 287 288
            pserver_startup = t.get_startup_program(
                current_endpoint, pserver_prog
            )
武毅 已提交
289 290 291 292
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())
293 294


295 296 297 298 299 300 301
def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

302 303 304
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
T
tianshuo78520a 已提交
305
        # the feed_target_names (the names of variables that will be fed
306 307
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
308 309 310 311 312
        [
            inference_program,
            feed_target_names,
            fetch_targets,
        ] = fluid.io.load_inference_model(save_dirname, exe)
313 314 315

        # Use the first data from paddle.dataset.movielens.test() as input
        assert feed_target_names[0] == "user_id"
316 317 318
        # Use create_lod_tensor(data, recursive_sequence_lengths, place) API
        # to generate LoD Tensor where `data` is a list of sequences of index
        # numbers, `recursive_sequence_lengths` is the length-based level of detail
319
        # (lod) info associated with `data`.
320 321
        # For example, data = [[10, 2, 3], [2, 3]] means that it contains
        # two sequences of indexes, of length 3 and 2, respectively.
322 323 324
        # Correspondingly, recursive_sequence_lengths = [[3, 2]] contains one
        # level of detail info, indicating that `data` consists of two sequences
        # of length 3 and 2, respectively.
P
peizhilin 已提交
325
        user_id = fluid.create_lod_tensor([[np.int64(1)]], [[1]], place)
326 327

        assert feed_target_names[1] == "gender_id"
P
peizhilin 已提交
328
        gender_id = fluid.create_lod_tensor([[np.int64(1)]], [[1]], place)
329 330

        assert feed_target_names[2] == "age_id"
P
peizhilin 已提交
331
        age_id = fluid.create_lod_tensor([[np.int64(0)]], [[1]], place)
332 333

        assert feed_target_names[3] == "job_id"
P
peizhilin 已提交
334
        job_id = fluid.create_lod_tensor([[np.int64(10)]], [[1]], place)
335 336

        assert feed_target_names[4] == "movie_id"
P
peizhilin 已提交
337
        movie_id = fluid.create_lod_tensor([[np.int64(783)]], [[1]], place)
338 339

        assert feed_target_names[5] == "category_id"
P
peizhilin 已提交
340
        category_id = fluid.create_lod_tensor(
341 342
            [np.array([10, 8, 9], dtype='int64')], [[3]], place
        )
343 344

        assert feed_target_names[6] == "movie_title"
P
peizhilin 已提交
345
        movie_title = fluid.create_lod_tensor(
346 347 348 349
            [np.array([1069, 4140, 2923, 710, 988], dtype='int64')],
            [[5]],
            place,
        )
350 351 352

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
353 354 355 356 357 358 359 360 361 362 363 364 365 366
        results = exe.run(
            inference_program,
            feed={
                feed_target_names[0]: user_id,
                feed_target_names[1]: gender_id,
                feed_target_names[2]: age_id,
                feed_target_names[3]: job_id,
                feed_target_names[4]: movie_id,
                feed_target_names[5]: category_id,
                feed_target_names[6]: movie_title,
            },
            fetch_list=fetch_targets,
            return_numpy=False,
        )
367
        print("inferred score: ", np.array(results[0]))
368 369 370 371 372 373 374


def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the inference model
375
    temp_dir = tempfile.TemporaryDirectory()
376 377 378
    save_dirname = os.path.join(
        temp_dir.name, "recommender_system.inference.model"
    )
379 380 381

    train(use_cuda, save_dirname)
    infer(use_cuda, save_dirname)
382
    temp_dir.cleanup()
383 384 385 386


if __name__ == '__main__':
    main(USE_GPU)