model.py 5.1 KB
Newer Older
T
tangwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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.

T
tangwei 已提交
15 16
import math
import paddle.fluid as fluid
T
tangwei 已提交
17

T
tangwei 已提交
18 19
from fleetrec.core.utils import envs
from fleetrec.core.model import Model as ModelBase
T
tangwei 已提交
20 21


T
tangwei 已提交
22
class Model(ModelBase):
T
tangwei 已提交
23
    def __init__(self, config):
T
tangwei 已提交
24
        ModelBase.__init__(self, config)
T
tangwei 已提交
25 26

    def input(self):
T
tangwei 已提交
27
        def sparse_inputs():
T
tangwei 已提交
28
            ids = envs.get_global_env("hyper_parameters.sparse_inputs_slots", None, self._namespace)
T
tangwei 已提交
29

T
tangwei 已提交
30
            sparse_input_ids = [
T
tangwei 已提交
31
                fluid.layers.data(name="S" + str(i),
T
tangwei 已提交
32 33
                                  shape=[1],
                                  lod_level=1,
T
tangwei12 已提交
34
                                  dtype="int64") for i in range(1, ids)
T
tangwei 已提交
35
            ]
T
tangwei 已提交
36
            return sparse_input_ids
T
tangwei 已提交
37 38

        def dense_input():
T
tangwei 已提交
39
            dim = envs.get_global_env("hyper_parameters.dense_input_dim", None, self._namespace)
T
tangwei 已提交
40

T
tangwei 已提交
41
            dense_input_var = fluid.layers.data(name="D",
T
tangwei12 已提交
42
                                                shape=[dim],
T
tangwei 已提交
43
                                                dtype="float32")
T
tangwei 已提交
44
            return dense_input_var
T
tangwei 已提交
45 46

        def label_input():
T
tangwei 已提交
47
            label = fluid.layers.data(name="click", shape=[1], dtype="int64")
T
tangwei 已提交
48
            return label
T
tangwei 已提交
49

T
tangwei 已提交
50 51 52
        self.sparse_inputs = sparse_inputs()
        self.dense_input = dense_input()
        self.label_input = label_input()
T
tangwei 已提交
53

T
bug fix  
tangwei 已提交
54 55
        self._data_var.append(self.dense_input)

T
tangwei 已提交
56 57
        for input in self.sparse_inputs:
            self._data_var.append(input)
T
bug fix  
tangwei 已提交
58

T
tangwei 已提交
59
        self._data_var.append(self.label_input)
T
tangwei 已提交
60

T
tangwei 已提交
61
        if self._platform != "LINUX":
T
tangwei 已提交
62
            self._data_loader = fluid.io.DataLoader.from_generator(
T
tangwei 已提交
63
                feed_list=self._data_var, capacity=64, use_double_buffer=False, iterable=False)
T
tangwei 已提交
64

T
tangwei 已提交
65
    def net(self):
T
tangwei 已提交
66
        trainer = envs.get_trainer()
T
tangwei 已提交
67

T
tangwei 已提交
68
        is_distributed = True if trainer == "CtrTrainer" else False
T
tangwei 已提交
69 70
        sparse_feature_number = envs.get_global_env("hyper_parameters.sparse_feature_number", None, self._namespace)
        sparse_feature_dim = envs.get_global_env("hyper_parameters.sparse_feature_dim", None, self._namespace)
T
tangwei 已提交
71
        sparse_feature_dim = 9 if trainer == "CtrTrainer" else sparse_feature_dim
T
tangwei 已提交
72

T
tangwei 已提交
73
        def embedding_layer(input):
T
tangwei 已提交
74 75 76
            emb = fluid.layers.embedding(
                input=input,
                is_sparse=True,
T
tangwei 已提交
77
                is_distributed=is_distributed,
T
tangwei12 已提交
78
                size=[sparse_feature_number, sparse_feature_dim],
T
tangwei 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
                param_attr=fluid.ParamAttr(
                    name="SparseFeatFactors",
                    initializer=fluid.initializer.Uniform()),
            )
            emb_sum = fluid.layers.sequence_pool(
                input=emb, pool_type='sum')
            return emb_sum

        def fc(input, output_size):
            output = fluid.layers.fc(
                input=input, size=output_size,
                act='relu', param_attr=fluid.ParamAttr(
                    initializer=fluid.initializer.Normal(
                        scale=1.0 / math.sqrt(input.shape[1]))))
            return output

        sparse_embed_seq = list(map(embedding_layer, self.sparse_inputs))
        concated = fluid.layers.concat(sparse_embed_seq + [self.dense_input], axis=1)

        fcs = [concated]
T
tangwei 已提交
99
        hidden_layers = envs.get_global_env("hyper_parameters.fc_sizes", None, self._namespace)
T
tangwei 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113

        for size in hidden_layers:
            fcs.append(fc(fcs[-1], size))

        predict = fluid.layers.fc(
            input=fcs[-1],
            size=2,
            act="softmax",
            param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
                scale=1 / math.sqrt(fcs[-1].shape[1]))),
        )

        self.predict = predict

T
tangwei12 已提交
114 115
    def avg_loss(self):
        cost = fluid.layers.cross_entropy(input=self.predict, label=self.label_input)
T
tangwei 已提交
116 117
        avg_cost = fluid.layers.reduce_mean(cost)
        self._cost = avg_cost
T
tangwei 已提交
118

T
tangwei 已提交
119
    def metrics(self):
T
tangwei 已提交
120 121 122 123
        auc, batch_auc, _ = fluid.layers.auc(input=self.predict,
                                             label=self.label_input,
                                             num_thresholds=2 ** 12,
                                             slide_steps=20)
T
tangwei 已提交
124 125
        self._metrics["AUC"] = auc
        self._metrics["BATCH_AUC"] = batch_auc
T
tangwei12 已提交
126

T
tangwei 已提交
127 128 129 130 131 132
    def train_net(self):
        self.input()
        self.net()
        self.avg_loss()
        self.metrics()

T
tangwei 已提交
133
    def optimizer(self):
T
tangwei 已提交
134
        learning_rate = envs.get_global_env("hyper_parameters.learning_rate", None, self._namespace)
T
tangwei 已提交
135 136 137
        optimizer = fluid.optimizer.Adam(learning_rate, lazy_mode=True)
        return optimizer

T
tangwei 已提交
138 139 140
    def infer_net(self):
        self.input()
        self.net()