nce_op.cc 11.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
W
wanghaoshuang 已提交
2

W
wanghaoshuang 已提交
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
W
wanghaoshuang 已提交
6

W
wanghaoshuang 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
W
wanghaoshuang 已提交
8

W
wanghaoshuang 已提交
9 10 11 12 13
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
wanghaoshuang 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/nce_op.h"
W
wanghaoshuang 已提交
16

17
#include <string>
Y
Yang Yang 已提交
18 19
#include <vector>

W
wanghaoshuang 已提交
20 21 22 23 24 25 26 27 28
namespace paddle {
namespace operators {

using framework::Tensor;

class NCEOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

29
  void InferShape(framework::InferShapeContext *ctx) const override {
30 31 32 33 34 35
    PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true);
    PADDLE_ENFORCE_EQ(ctx->HasInput("Label"), true);
    PADDLE_ENFORCE_EQ(ctx->HasInput("Weight"), true);
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Cost"), true);
    PADDLE_ENFORCE_EQ(ctx->HasOutput("SampleLogits"), true);
    PADDLE_ENFORCE_EQ(ctx->HasOutput("SampleLabels"), true);
W
wanghaoshuang 已提交
36

W
wanghaoshuang 已提交
37
    auto x_dims = ctx->GetInputDim("Input");
W
wanghaoshuang 已提交
38
    auto label_dims = ctx->GetInputDim("Label");
39
    if (ctx->IsRuntime() || (x_dims[0] > 0 && label_dims[0] > 0)) {
40 41 42 43 44 45 46
      PADDLE_ENFORCE_EQ(
          x_dims[0], label_dims[0],
          "ShapeError: the first dimension of Input(Input) and Input(Label) "
          "should be equal in runtime. But received: Input(Input)'s shape = "
          "[%s] with 1st dim =  %d, Input(Label)'s shape = [%s] with 1st "
          "dim = %d.",
          x_dims, x_dims[0], label_dims, label_dims[0]);
47
    }
W
wanghaoshuang 已提交
48 49
    int num_true_classes = label_dims.size() == 2 ? label_dims[1] : 1;
    if (ctx->HasInput("Bias")) {
50 51 52 53 54 55 56
      PADDLE_ENFORCE_EQ(
          ctx->GetInputDim("Weight")[0], ctx->GetInputDim("Bias")[0],
          "ShapeError: the first dimension of Input(Weight) and Input(Bias) "
          "should be equal. But received: Input(Weight)'s shape = [%s] with "
          "1st dim = %d, Input(Bias)'s shape = [%s] with 1st dim = %d.",
          ctx->GetInputDim("Weight"), ctx->GetInputDim("Weight")[0],
          ctx->GetInputDim("Bias"), ctx->GetInputDim("Bias")[0]);
W
wanghaoshuang 已提交
57
    }
W
wanghaoshuang 已提交
58 59
    auto num_neg_samples = ctx->Attrs().Get<int>("num_neg_samples");
    auto num_total_classes = ctx->Attrs().Get<int>("num_total_classes");
W
wanghaoshuang 已提交
60 61
    std::vector<int> custom_neg_classes =
        ctx->Attrs().Get<std::vector<int>>("custom_neg_classes");
62 63 64 65 66 67 68
    PADDLE_ENFORCE_EQ(
        num_total_classes, ctx->GetInputDim("Weight")[0],
        "ShapeError: the number of total classes should be equal to the first "
        "dimension of Input(Weight). But received: Attr(num_total_classes) = "
        "%d, Input(Weight)'s shape = [%s] with 1st dim = %d.",
        num_total_classes, ctx->GetInputDim("Weight"),
        ctx->GetInputDim("Weight")[0]);
W
wanghaoshuang 已提交
69
    if (custom_neg_classes.size() > 0) {
70 71 72 73 74 75
      PADDLE_ENFORCE_EQ(
          custom_neg_classes.size(), static_cast<size_t>(num_neg_samples),
          "ShapeError: the size of Attr(custom_neg_classes) should be equal "
          "to the number of negative samples. But received: "
          "custom_neg_classes.size() = %d, num_neg_samples = %d.",
          custom_neg_classes.size(), num_neg_samples);
W
wanghaoshuang 已提交
76
    }
W
wanghaoshuang 已提交
77
    // set dims of output(Out)
W
wanghaoshuang 已提交
78
    std::vector<int64_t> out_dims;
W
wanghaoshuang 已提交
79
    out_dims.push_back(x_dims[0]);
W
wanghaoshuang 已提交
80
    out_dims.push_back(1);
W
wanghaoshuang 已提交
81
    ctx->SetOutputDim("Cost", framework::make_ddim(out_dims));
W
wanghaoshuang 已提交
82 83

    // set dims of output(SampleOut)
W
wanghaoshuang 已提交
84
    std::vector<int64_t> sample_out_dims;
W
wanghaoshuang 已提交
85
    sample_out_dims.push_back(x_dims[0]);
86 87
    sample_out_dims.push_back(
        (num_true_classes == -1) ? -1 : (num_neg_samples + num_true_classes));
W
wanghaoshuang 已提交
88 89 90
    ctx->SetOutputDim("SampleLogits", framework::make_ddim(sample_out_dims));
    ctx->SetOutputDim("SampleLabels", framework::make_ddim(sample_out_dims));
  }
W
wanghaoshuang 已提交
91 92

 protected:
93
  framework::OpKernelType GetExpectedKernelType(
94
      const framework::ExecutionContext &ctx) const override {
Y
Yu Yang 已提交
95 96
    return framework::OpKernelType(ctx.Input<Tensor>("Input")->type(),
                                   platform::CPUPlace());
W
wanghaoshuang 已提交
97
  }
W
wanghaoshuang 已提交
98 99 100 101
};

class NCEOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
102
  void Make() override {
W
wanghaoshuang 已提交
103
    AddInput("Input", "(Tensor) A tensor of shape [batch_size, dim].");
W
wanghaoshuang 已提交
104 105 106 107 108 109 110 111
    AddInput(
        "Label",
        "(Tensor) A tensor of shape [batch_size, num_true_class]. "
        "'num_true_class' is the number of target classes in each sample."
        "The number of target classes per sample should be same. "
        "If you have a variable number of target classes, "
        "you can pad them out to a constant number by either repeating them"
        " or by padding with an otherwise unused class.)");
W
wanghaoshuang 已提交
112 113 114
    AddInput("Weight",
             "(Tensor) A tensor of shape [num_class, dim]. 'num_class' is the "
             "total number of class.");
W
wanghaoshuang 已提交
115 116 117 118
    AddInput(
        "Bias",
        "(Tensor) A tensor of shape [num_class, 1]. 'num_class' is the total "
        "number of class. It is a dispensable input.")
W
wanghaoshuang 已提交
119 120
        .AsDispensable();
    AddInput("SampleWeight",
W
wanghaoshuang 已提交
121
             "(Tensor) A tensor of shape [batch_size, 1] storing a weight for "
W
wanghaoshuang 已提交
122 123 124
             "each sample. And it is a dispensable input. The default value of "
             "sample is 1.")
        .AsDispensable();
125 126

    AddInput(
127
        "CustomDistProbs",
128 129 130 131
        "(Tensor) It is used in 'CostumDist' sampler. "
        "It is a tensor with shape [num_total_classes]."
        "The i-th element is the probsbility of the i-th class being sampled.")
        .AsDispensable();
132 133 134 135 136 137 138 139 140 141 142 143 144
    AddInput(
        "CustomDistAlias",
        "(Tensor) It is used in 'CostumDist' sampler. "
        "It is a tensor with shape [num_total_classes]."
        "The i-th element is the probsbility of the i-th class being sampled.")
        .AsDispensable();
    AddInput(
        "CustomDistAliasProbs",
        "(Tensor) It is used in 'CostumDist' sampler. "
        "It is a tensor with shape [num_total_classes]."
        "The i-th element is the probsbility of the i-th class being sampled.")
        .AsDispensable();

W
wanghaoshuang 已提交
145
    AddOutput("Cost",
W
wanghaoshuang 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
              "(Tensor) A tensor of shape [batch_size, 1]. Cost of samples.");
    AddOutput("SampleLogits",
              "An intermediate tensor of shape[batch_size, num_neg_samples + "
              "num_pos_samples]."
              "This tensor is output of forward kernel and used in backward "
              "kernel to compute grads."
              "Given X is  the dot product of input tensor and sampled labels' "
              "weights."
              "Then 'SampleLogits' is sigmoid(X).")
        .AsIntermediate();
    AddOutput("SampleLabels",
              "An intermediate tensor of shape[batch_size, num_neg_samples + "
              "num_pos_samples]."
              "This tensor is output of forward kernel and used in backward "
              "kernel to compute grads."
              "")
        .AsIntermediate();
163

W
wanghaoshuang 已提交
164 165 166 167
    AddAttr<int>("num_total_classes",
                 "Total number of classes in all samples.");
    AddAttr<int>("num_neg_samples",
                 "The number of negative classes. The default value is 10.")
W
wanghaoshuang 已提交
168
        .SetDefault(10);
169 170 171 172 173 174 175 176
    AddAttr<int>("sampler",
                 "(int) Which sampler to be used to sample negative class."
                 "0: Uniform; 1: LogUniform; 2: CostumDist.")
        .SetDefault(0);
    AddAttr<int>("seed",
                 "(int) The seed used in sampler. If it is 0, "
                 "the sampler will generate a seed randomly.")
        .SetDefault(0);
177 178
    AddAttr<bool>("is_sparse", "(boolean, default false) Sparse update.")
        .SetDefault(false);
179

T
tangwei12 已提交
180 181 182
    // for parameter prefetch
    AddAttr<bool>("remote_prefetch", "").SetDefault(false);
    AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0);
Q
Qiao Longfei 已提交
183 184 185
    AddAttr<std::vector<int64_t>>("height_sections",
                                  "Height for each output SelectedRows.")
        .SetDefault(std::vector<int64_t>({}));
T
tangwei12 已提交
186 187 188 189 190 191 192 193 194 195 196 197
    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({});

W
wanghaoshuang 已提交
198 199 200 201
    AddAttr<std::vector<int>>("custom_neg_classes",
                              "This attribute only be used in unitest. Classes "
                              "in this list wiil be used as negative classes "
                              "for every samples. Under normal conditions, "
Y
Yang Yu 已提交
202 203
                              "user should avoid setting this attribute.")
        .SetDefault({});
W
wanghaoshuang 已提交
204
    AddComment(R"DOC(
M
minqiyang 已提交
205 206 207
Compute and return the noise-contrastive estimation training loss. See
`Noise-contrastive estimation: A new estimation principle for unnormalized
statistical models
Y
Yibing Liu 已提交
208
 <http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf>`_.
W
wanghaoshuang 已提交
209
By default this operator uses a uniform distribution for sampling.
W
wanghaoshuang 已提交
210 211 212 213 214 215 216 217
)DOC");
  }
};

class NCEOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

218
  void InferShape(framework::InferShapeContext *ctx) const override {
W
wanghaoshuang 已提交
219 220 221 222 223 224
    PADDLE_ENFORCE(ctx->HasInput("Input"));
    PADDLE_ENFORCE(ctx->HasInput("Weight"));
    PADDLE_ENFORCE(ctx->HasInput("Cost"));
    PADDLE_ENFORCE(ctx->HasInput("SampleLogits"));
    PADDLE_ENFORCE(ctx->HasInput("SampleLabels"));
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Cost")),
W
wanghaoshuang 已提交
225
                   "The input(Out@GRAD) should not be null.");
W
wanghaoshuang 已提交
226

W
wanghaoshuang 已提交
227 228
    auto x_dims = ctx->GetInputDim("Input");
    auto x_grad_name = framework::GradVarName("Input");
W
wanghaoshuang 已提交
229 230 231 232
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }

W
wanghaoshuang 已提交
233 234
    auto w_dims = ctx->GetInputDim("Weight");
    auto w_grad_name = framework::GradVarName("Weight");
W
wanghaoshuang 已提交
235 236 237 238
    if (ctx->HasOutput(w_grad_name)) {
      ctx->SetOutputDim(w_grad_name, w_dims);
    }

W
wanghaoshuang 已提交
239
    auto bias_grad_name = framework::GradVarName("Bias");
W
wanghaoshuang 已提交
240
    if (ctx->HasOutput(bias_grad_name)) {
W
wanghaoshuang 已提交
241
      auto bias_dims = ctx->GetInputDim("Bias");
W
wanghaoshuang 已提交
242 243 244
      ctx->SetOutputDim(bias_grad_name, bias_dims);
    }
  }
W
wanghaoshuang 已提交
245 246

 protected:
247
  framework::OpKernelType GetExpectedKernelType(
248
      const framework::ExecutionContext &ctx) const override {
Y
Yu Yang 已提交
249 250
    return framework::OpKernelType(ctx.Input<Tensor>("Input")->type(),
                                   platform::CPUPlace());
W
wanghaoshuang 已提交
251
  }
W
wanghaoshuang 已提交
252 253
};

254 255
class NCEOpGradVarTypeInference : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
256 257
  void operator()(framework::InferVarTypeContext *ctx) const override {
    auto weight_grad = ctx->Output(framework::GradVarName("Weight")).front();
258

M
minqiyang 已提交
259
    auto attr = ctx->GetAttr("is_sparse");
260 261
    bool is_sparse = boost::get<bool>(attr);
    if (is_sparse) {
262
      VLOG(3) << "nce_op_grad op " << weight_grad << " and "
M
minqiyang 已提交
263
              << " is set to SelectedRows";
M
minqiyang 已提交
264
      ctx->SetType(weight_grad, framework::proto::VarType::SELECTED_ROWS);
265
    } else {
266
      VLOG(3) << "nce_op_grad op " << weight_grad << " and "
M
minqiyang 已提交
267
              << " is set to LoDTensor";
M
minqiyang 已提交
268
      ctx->SetType(weight_grad, framework::proto::VarType::LOD_TENSOR);
269
    }
M
minqiyang 已提交
270
    ctx->SetDataType(weight_grad, ctx->GetDataType(ctx->Input("Input")[0]));
271 272 273
  }
};

W
wanghaoshuang 已提交
274 275 276 277
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
S
sneaxiy 已提交
278 279 280
REGISTER_OPERATOR(nce, ops::NCEOp,
                  paddle::framework::DefaultGradOpDescMaker<true>,
                  ops::NCEOpMaker);
281
REGISTER_OPERATOR(nce_grad, ops::NCEOpGrad, ops::NCEOpGradVarTypeInference);
W
wanghaoshuang 已提交
282 283
REGISTER_OP_CPU_KERNEL(nce, ops::NCEKernel<paddle::platform::CPUPlace, float>,
                       ops::NCEKernel<paddle::platform::CPUPlace, double>);
W
wanghaoshuang 已提交
284
REGISTER_OP_CPU_KERNEL(nce_grad,
W
wanghaoshuang 已提交
285 286
                       ops::NCEGradKernel<paddle::platform::CPUPlace, float>,
                       ops::NCEGradKernel<paddle::platform::CPUPlace, double>);