hierarchical_sigmoid_op.cc 10.6 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. */

15
#include <string>
W
weixing02 已提交
16
#include <vector>
17 18 19 20 21

#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/phi/infermeta/multiary.h"

Y
Yancey1989 已提交
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 64 65 66
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;
Y
Yancey1989 已提交
67 68

 protected:
W
weixing02 已提交
69
  framework::OpKernelType GetExpectedKernelType(
Y
Yancey1989 已提交
70
      const framework::ExecutionContext& ctx) const override {
71 72
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
Y
Yancey1989 已提交
73
  }
Y
Yancey1989 已提交
74 75
};

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

157 158 159 160
/*
 * Inputs: X, W, Label, PathTable, PathCode, PreOut, Out@GRAD
 * Outputs: X@GRAD, W@GRAD, Bias@GRAD
 */
H
hong 已提交
161 162
template <typename T>
class HierarchicalSigmoidGradMaker : public framework::SingleGradOpMaker<T> {
163
 public:
H
hong 已提交
164
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
165

166
  void Apply(GradOpPtr<T> op) const override {
167 168
    op->SetType(this->ForwardOpType() + "_grad");
    // Inputs: X, W, Label, PathTable, PathCode, PreOut, Out@GRAD
H
hong 已提交
169 170 171 172 173 174 175 176
    op->SetInput("X", this->Input("X"));
    op->SetInput("W", this->Input("W"));
    op->SetInput("Bias", this->Input("Bias"));
    op->SetInput("Label", this->Input("Label"));
    op->SetInput("PathTable", this->Input("PathTable"));
    op->SetInput("PathCode", this->Input("PathCode"));
    op->SetInput("PreOut", this->Output("PreOut"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
177 178

    // Outputs: X@GRAD, W@GRAD, Bias@GRAD
H
hong 已提交
179 180 181 182
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("W"), this->InputGrad("W"));
    op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias"));
    op->SetAttrMap(this->Attrs());
183 184 185
  }
};

W
weixing02 已提交
186 187 188 189
class HierarchicalSigmoidGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
190 191
    OP_INOUT_CHECK(ctx->HasInput("W"), "Input", "W", "hsigmoid_grad");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "hsigmoid_grad");
192 193 194 195
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   "Out@Grad",
                   "hsigmoid_grad");
196
    OP_INOUT_CHECK(ctx->HasInput("PreOut"), "Input", "PreOut", "hsigmoid_grad");
197 198 199 200 201 202 203 204
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("W")),
                   "Output",
                   "W@Grad",
                   "hsigmoid_grad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   "X@Grad",
                   "hsigmoid_grad");
205 206 207 208

    if (ctx->HasOutput(framework::GradVarName("Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Bias"),
                        ctx->GetInputDim("Bias"));
J
JiabinYang 已提交
209
    }
210
    ctx->SetOutputDim(framework::GradVarName("W"), ctx->GetInputDim("W"));
W
weixing02 已提交
211
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
J
JiabinYang 已提交
212
    ctx->ShareLoD("X", /*->*/ framework::GradVarName("X"));
W
weixing02 已提交
213 214 215 216 217
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
218 219
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
W
weixing02 已提交
220 221 222
  }
};

J
JiabinYang 已提交
223 224 225
class HierarchicalSigmoidGradOpGradVarTypeInference
    : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
226
  void operator()(framework::InferVarTypeContext* ctx) const override {
227 228 229 230
    auto w_grad_var_name = framework::GradVarName("W");
    auto bias_grad_var_name = framework::GradVarName("Bias");
    if (ctx->HasOutput(bias_grad_var_name)) {
      VLOG(3) << "hierarchical_sigmoid_grad op "
231 232
              << framework::GradVarName("Bias")
              << " is set to phi::DenseTensor";
233 234
      ctx->SetOutputType(bias_grad_var_name,
                         framework::proto::VarType::LOD_TENSOR);
235
    }
236

M
minqiyang 已提交
237
    auto attr = ctx->GetAttr("is_sparse");
R
Ruibiao Chen 已提交
238
    bool is_sparse = PADDLE_GET(bool, attr);
J
JiabinYang 已提交
239
    if (is_sparse) {
240 241
      VLOG(3) << "hierarchical_sigmoid_grad op " << framework::GradVarName("W")
              << " is set to SelectedRows";
242 243
      ctx->SetOutputType(w_grad_var_name,
                         framework::proto::VarType::SELECTED_ROWS);
J
JiabinYang 已提交
244
    } else {
245
      VLOG(3) << "hierarchical_sigmoid_grad op " << framework::GradVarName("W")
246
              << " is set to phi::DenseTensor";
247 248
      ctx->SetOutputType(w_grad_var_name,
                         framework::proto::VarType::LOD_TENSOR);
249
    }
250 251

    ctx->SetOutputDataType(w_grad_var_name, ctx->GetInputDataType("W"));
J
JiabinYang 已提交
252 253 254
  }
};

255
DECLARE_NO_NEED_BUFFER_VARS_INFERER(
256
    HierarchicalSigmoidGradOpNoNeedBufferVarInferer, "Bias");
257

Y
Yancey1989 已提交
258 259 260 261
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
262 263
DECLARE_INFER_SHAPE_FUNCTOR(hierarchical_sigmoid,
                            HierarchicalSigmoidInferShapeFunctor,
264
                            PD_INFER_META(phi::HSigmoidLossInferMeta));
265 266
REGISTER_OPERATOR(hierarchical_sigmoid,
                  ops::HierarchicalSigmoidOp,
267 268 269 270
                  ops::HierarchicalSigmoidOpMaker<int>,
                  ops::HierarchicalSigmoidGradMaker<paddle::framework::OpDesc>,
                  ops::HierarchicalSigmoidGradMaker<paddle::imperative::OpBase>,
                  HierarchicalSigmoidInferShapeFunctor);
271 272
REGISTER_OPERATOR(hierarchical_sigmoid_grad,
                  ops::HierarchicalSigmoidGradOp,
273
                  ops::HierarchicalSigmoidGradOpGradVarTypeInference,
274
                  ops::HierarchicalSigmoidGradOpNoNeedBufferVarInferer);