hierarchical_sigmoid_op.cc 11.3 KB
Newer Older
Y
Yancey1989 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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. */

W
weixing02 已提交
15
#include "paddle/fluid/operators/hierarchical_sigmoid_op.h"
16
#include <string>
W
weixing02 已提交
17
#include <vector>
Y
Yancey1989 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
namespace paddle {
namespace operators {

/**
 * Organize the classes into a binary tree. At each node, a sigmoid function
 * is used to calculate the probability of belonging to the right branch.
 * This idea is from "F. Morin, Y. Bengio (AISTATS 05):
 * Hierarchical Probabilistic Neural Network Language Model."
 *
 * Here we uses a simple way of making the binary tree.
 * Assuming the number of classes C = 6,
 * The classes are organized as a binary tree in the following way:
 *
 * @code{.py}
 * *-*-*- 2
 * | | |- 3
 * | |
 * | |-*- 4
 * |   |- 5
 * |
 * |-*- 0
 *   |- 1
 * @endcode
 *
 * where * indicates an internal node, and each leaf node represents a class.
 * - Node 0 ... C-2 are internal nodes.
 * - Node C-1 ... 2C-2 are leaf nodes.
 * - Class c is represented by leaf node \f$c+C-1\f$.
 *
 * We assign an id for each node:
 * - the id of root be 0.
 * - the left child of a node i is 2*i+1.
 * - the right child of a node i is 2*i+2.
 *
 * It's easy to see that:
 * - the parent of node i is \f$\left\lfloor(i-1)/2\right\rfloor\f$.
 * - the j-th level ancestor of node i is
 * \f$\left\lfloor(i+1)/2^{j+1}\right\rfloor - 1\f$.
 * - A node i is a left child of its parent if \f$(i-1)\%2==0\f$.
 *
 */

class HierarchicalSigmoidOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
Y
Yancey1989 已提交
64
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
W
weixing02 已提交
65
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should not be null.");
Y
Yancey1989 已提交
66
    PADDLE_ENFORCE(ctx->HasInput("W"), "Input(W) should not be null.");
Y
Yancey1989 已提交
67
    PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null.");
W
weixing02 已提交
68 69
    PADDLE_ENFORCE(ctx->HasOutput("PreOut"),
                   "Output(PreOut) should not be null.");
70 71 72 73 74
    auto with_prefetch = ctx->Attrs().Get<bool>("remote_prefetch");
    if (with_prefetch) {
      PADDLE_ENFORCE(ctx->HasOutput("W_Out"),
                     "Output(W_Out) should not be null.");
    }
Y
Yancey1989 已提交
75
    const int64_t batch_size = ctx->GetInputDim("X")[0];
Y
Yancey1989 已提交
76
    std::vector<int64_t> output_shape({batch_size, 1});
Y
Yancey1989 已提交
77
    ctx->SetOutputDim("Out", framework::make_ddim(output_shape));
J
JiabinYang 已提交
78
    ctx->ShareLoD("X", /*->*/ "Out");
Y
Yancey1989 已提交
79
  }
Y
Yancey1989 已提交
80 81

 protected:
W
weixing02 已提交
82
  framework::OpKernelType GetExpectedKernelType(
Y
Yancey1989 已提交
83
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
84 85
    return framework::OpKernelType(ctx.Input<framework::LoDTensor>("X")->type(),
                                   ctx.GetPlace());
Y
Yancey1989 已提交
86
  }
Y
Yancey1989 已提交
87 88
};

89 90 91 92
/*
 * Inputs: X, W, Label, PathTable, PathCode, Bias
 * Outputs: Out, PreOut, W_out
 */
W
weixing02 已提交
93
template <typename AttrType>
Y
Yancey1989 已提交
94 95
class HierarchicalSigmoidOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
W
weixing02 已提交
96
  void Make() override {
Y
Yancey1989 已提交
97
    AddInput("X",
J
JiabinYang 已提交
98
             "(LoDTensor, required) The input tensor with shape [N, D], "
G
guosheng 已提交
99
             "where N is the size of mini-batch, and D is the feature size.");
Y
Yancey1989 已提交
100
    AddInput("W",
J
JiabinYang 已提交
101
             "(LoDTensor, required), The parameters of hierarchical "
G
guosheng 已提交
102
             "sigmoid operator, each of them is a 2-D tensor, the shape is"
103
             "[K, D]. Which K is the num of non-leaf node in Path Tree");
W
weixing02 已提交
104
    AddInput("Label",
J
JiabinYang 已提交
105
             "(LoDTensor, required), The labels of training data. It's a"
G
guosheng 已提交
106
             "tensor with shape [N, 1].");
107
    AddInput("PathTable",
J
JiabinYang 已提交
108
             "(LoDTensor, optional), The Path Table from root to current word"
109 110
             "it should have shape like [N, L], L is the length of the Path")
        .AsDispensable();
J
JiabinYang 已提交
111
    AddInput(
J
JiabinYang 已提交
112
        "PathCode",
J
JiabinYang 已提交
113 114 115
        "(LoDTensor, optional), The Code on each Node of the Path from root "
        "to current word"
        "it should have shape like [N, L], L is the length of the Path")
116
        .AsDispensable();
Y
Yancey1989 已提交
117
    AddInput("Bias",
J
JiabinYang 已提交
118
             "(LoDTensor, optional), The bias is a tensor with shape or "
119
             "[num_classes, 1]"
120 121
             "[num_classes - 1, 1].")
        .AsDispensable();
J
JiabinYang 已提交
122 123 124 125
    AddOutput(
        "Out",
        "(LoDTensor, required) The output of hierarchical sigmoid operator."
        "The shape is [N, 1].");
W
weixing02 已提交
126
    AddOutput("PreOut",
J
JiabinYang 已提交
127
              "(LoDTensor, required) A intermedia 2-D tensor with shape "
G
guosheng 已提交
128 129
              "[batch_size, code_length], where code_length represents the "
              "maximum path length from root to leaf nodes.")
W
weixing02 已提交
130
        .AsIntermediate();
131 132 133 134 135
    AddOutput(
        "W_Out",
        "(LoDTensor, optinal) using input 'W' as Output to make it mutable"
        "When we are using prefetch")
        .AsIntermediate();
J
JiabinYang 已提交
136
    AddAttr<AttrType>("num_classes", "(int, optional), The number of classes")
Y
Yancey1989 已提交
137
        .SetDefault(2);
138 139 140
    // for parameter prefetch
    AddAttr<bool>("remote_prefetch", "").SetDefault(false);
    AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0);
Q
Qiao Longfei 已提交
141 142 143
    AddAttr<std::vector<int64_t>>("height_sections",
                                  "Height for each output SelectedRows.")
        .SetDefault(std::vector<int64_t>({}));
144 145 146 147 148 149 150 151 152 153 154
    AddAttr<std::vector<std::string>>(
        "epmap",
        "(string vector, default 127.0.0.1:6164)"
        "Server endpoints in the order of input variables for mapping")
        .SetDefault({});
    AddAttr<std::vector<std::string>>(
        "table_names",
        "(string vector, the splited table names that will be fetched from "
        "parameter server)"
        "in the order of input variables for mapping")
        .SetDefault({});
Y
Yancey1989 已提交
155 156
    AddComment(R"DOC(
The hierarchical sigmoid operator organize the classes into a binary tree.
W
weixing02 已提交
157
At each node, a sigmoid function is used to calculate the probability of
W
weixing02 已提交
158 159
belonging to the right branch. This idea is from
"F. Morin, Y. Bengio (AISTATS 05):
Y
Yancey1989 已提交
160 161
Hierarchical Probabilistic Neural Network Language Model."
      )DOC");
J
JiabinYang 已提交
162 163 164 165
    AddAttr<bool>("is_sparse",
                  "(boolean, default false) "
                  "Sparse update.")
        .SetDefault(false);
Y
Yancey1989 已提交
166 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 194 195 196 197 198 199
/*
 * Inputs: X, W, Label, PathTable, PathCode, PreOut, Out@GRAD
 * Outputs: X@GRAD, W@GRAD, Bias@GRAD
 */
class HierarchicalSigmoidGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* op = new framework::OpDesc();
    op->SetType(this->ForwardOpType() + "_grad");
    // Inputs: X, W, Label, PathTable, PathCode, PreOut, Out@GRAD
    op->SetInput("X", Input("X"));
    op->SetInput("W", Input("W"));
    op->SetInput("Bias", Input("Bias"));
    op->SetInput("Label", Input("Label"));
    op->SetInput("PathTable", Input("PathTable"));
    op->SetInput("PathCode", Input("PathCode"));
    op->SetInput("PreOut", Output("PreOut"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));

    // Outputs: X@GRAD, W@GRAD, Bias@GRAD
    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    op->SetOutput(framework::GradVarName("W"), InputGrad("W"));
    op->SetOutput(framework::GradVarName("Bias"), InputGrad("Bias"));
    op->SetAttrMap(Attrs());

    return std::unique_ptr<framework::OpDesc>(op);
  }
};

W
weixing02 已提交
200 201 202 203 204
class HierarchicalSigmoidGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("W"), "Input(W) should not be null.");
W
weixing02 已提交
205
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should not be null.");
J
JiabinYang 已提交
206 207
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@Grad) should not be null");
W
weixing02 已提交
208 209 210
    PADDLE_ENFORCE(ctx->HasInput("PreOut"),
                   "Input(Preout) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("W")),
J
JiabinYang 已提交
211 212 213
                   "Output(W@Grad should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")),
                   "Output(X@Grad should not be null.");
214 215 216 217

    if (ctx->HasOutput(framework::GradVarName("Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Bias"),
                        ctx->GetInputDim("Bias"));
J
JiabinYang 已提交
218
    }
219
    ctx->SetOutputDim(framework::GradVarName("W"), ctx->GetInputDim("W"));
W
weixing02 已提交
220
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
J
JiabinYang 已提交
221
    ctx->ShareLoD("X", /*->*/ framework::GradVarName("X"));
W
weixing02 已提交
222 223 224 225 226
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
227 228
    return framework::OpKernelType(ctx.Input<framework::LoDTensor>("X")->type(),
                                   ctx.GetPlace());
W
weixing02 已提交
229 230 231
  }
};

J
JiabinYang 已提交
232 233 234
class HierarchicalSigmoidGradOpGradVarTypeInference
    : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
235 236 237
  void operator()(framework::InferVarTypeContext* ctx) const override {
    auto w_grad_var_name = ctx->Output(framework::GradVarName("W")).front();
    auto bias_grad_var_name_vec = ctx->Output(framework::GradVarName("Bias"));
238 239 240 241
    std::string bias_grad_var_name;
    bool hasBias = false;
    if (bias_grad_var_name_vec.size()) {
      hasBias = true;
M
minqiyang 已提交
242
      bias_grad_var_name = ctx->Output(framework::GradVarName("Bias")).front();
243
    }
M
minqiyang 已提交
244
    auto attr = ctx->GetAttr("is_sparse");
J
JiabinYang 已提交
245 246
    bool is_sparse = boost::get<bool>(attr);
    if (is_sparse) {
247 248
      VLOG(3) << "hierarchical_sigmoid_grad op " << framework::GradVarName("W")
              << " is set to SelectedRows";
M
minqiyang 已提交
249
      ctx->SetType(w_grad_var_name, framework::proto::VarType::SELECTED_ROWS);
J
JiabinYang 已提交
250
    } else {
251 252
      VLOG(3) << "hierarchical_sigmoid_grad op " << framework::GradVarName("W")
              << " is set to LoDTensor";
M
minqiyang 已提交
253
      ctx->SetType(w_grad_var_name, framework::proto::VarType::LOD_TENSOR);
254 255
    }
    if (hasBias) {
256 257
      VLOG(3) << "hierarchical_sigmoid_grad op "
              << framework::GradVarName("Bias") << " is set to LoDTensor";
M
minqiyang 已提交
258
      ctx->SetType(bias_grad_var_name, framework::proto::VarType::LOD_TENSOR);
J
JiabinYang 已提交
259
    }
M
minqiyang 已提交
260
    ctx->SetDataType(w_grad_var_name, ctx->GetDataType(ctx->Input("W")[0]));
J
JiabinYang 已提交
261 262 263
  }
};

Y
Yancey1989 已提交
264 265 266 267
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
W
weixing02 已提交
268 269
REGISTER_OPERATOR(hierarchical_sigmoid, ops::HierarchicalSigmoidOp,
                  ops::HierarchicalSigmoidOpMaker<int>,
270
                  ops::HierarchicalSigmoidGradMaker);
J
JiabinYang 已提交
271 272
REGISTER_OPERATOR(hierarchical_sigmoid_grad, ops::HierarchicalSigmoidGradOp,
                  ops::HierarchicalSigmoidGradOpGradVarTypeInference);
W
weixing02 已提交
273 274 275 276 277 278 279 280 281 282 283
REGISTER_OP_CPU_KERNEL(
    hierarchical_sigmoid,
    ops::HierarchicalSigmoidOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::HierarchicalSigmoidOpKernel<paddle::platform::CPUDeviceContext,
                                     double>);
REGISTER_OP_CPU_KERNEL(
    hierarchical_sigmoid_grad,
    ops::HierarchicalSigmoidGradOpKernel<paddle::platform::CPUDeviceContext,
                                         float>,
    ops::HierarchicalSigmoidGradOpKernel<paddle::platform::CPUDeviceContext,
                                         double>);