nce_op.cc 6.5 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* 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. */

#include "paddle/operators/nce_op.h"

namespace paddle {
namespace operators {

using framework::Tensor;

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

  void InferShape(framework::InferShapeContext* ctx) const override {
W
wanghaoshuang 已提交
27
    PADDLE_ENFORCE(ctx->HasInput("Input"));
W
wanghaoshuang 已提交
28
    PADDLE_ENFORCE(ctx->HasInput("Label"));
W
wanghaoshuang 已提交
29 30
    PADDLE_ENFORCE(ctx->HasInput("Weight"));
    PADDLE_ENFORCE(ctx->HasOutput("Cost"));
W
wanghaoshuang 已提交
31 32 33
    PADDLE_ENFORCE(ctx->HasOutput("SampleLogits"));
    PADDLE_ENFORCE(ctx->HasOutput("SampleLabels"));

W
wanghaoshuang 已提交
34
    auto x_dims = ctx->GetInputDim("Input");
W
wanghaoshuang 已提交
35 36
    auto label_dims = ctx->GetInputDim("Label");
    PADDLE_ENFORCE_EQ(x_dims[0], label_dims[0]);
W
wanghaoshuang 已提交
37 38 39 40
    int num_true_classes = label_dims.size() == 2 ? label_dims[1] : 1;
    if (ctx->HasInput("Bias")) {
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("Weight")[0],
                        ctx->GetInputDim("Bias")[0]);
W
wanghaoshuang 已提交
41
    }
W
wanghaoshuang 已提交
42 43 44 45 46
    auto num_sampled_classes = ctx->Attrs().Get<int>("num_sampled_classes");
    auto num_classes = ctx->Attrs().Get<int>("num_classes");
    std::vector<int> sampled_labels =
        ctx->Attrs().Get<std::vector<int>>("sampled_labels");
    PADDLE_ENFORCE_EQ(num_classes, ctx->GetInputDim("Weight")[0]);
W
wanghaoshuang 已提交
47
    PADDLE_ENFORCE_LT(num_sampled_classes, num_classes);
W
wanghaoshuang 已提交
48 49 50 51
    if (sampled_labels.size() > 0) {
      PADDLE_ENFORCE_EQ(sampled_labels.size(),
                        static_cast<size_t>(num_sampled_classes));
    }
W
wanghaoshuang 已提交
52
    // set dims of output(Out)
W
wanghaoshuang 已提交
53
    std::vector<int64_t> out_dims;
W
wanghaoshuang 已提交
54
    out_dims.push_back(x_dims[0]);
W
wanghaoshuang 已提交
55
    ctx->SetOutputDim("Cost", framework::make_ddim(out_dims));
W
wanghaoshuang 已提交
56 57

    // set dims of output(SampleOut)
W
wanghaoshuang 已提交
58
    std::vector<int64_t> sample_out_dims;
W
wanghaoshuang 已提交
59
    sample_out_dims.push_back(x_dims[0]);
W
wanghaoshuang 已提交
60
    sample_out_dims.push_back(num_sampled_classes + num_true_classes);
W
wanghaoshuang 已提交
61 62 63
    ctx->SetOutputDim("SampleLogits", framework::make_ddim(sample_out_dims));
    ctx->SetOutputDim("SampleLabels", framework::make_ddim(sample_out_dims));
  }
W
wanghaoshuang 已提交
64 65 66 67 68 69 70 71

 protected:
  framework::OpKernelType GetKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("Input")->type()),
        ctx.device_context());
  }
W
wanghaoshuang 已提交
72 73 74 75 76 77
};

class NCEOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  NCEOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
W
wanghaoshuang 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    AddInput("Input", "(Tensor) A tensor of shape [batch_size, dim].");
    AddInput("Label",
             "(Tensor) A tensor of shape [batch_size, num_true_class]. "
             "'num_true_class' is the number of target class in each sample.");
    AddInput("Weight",
             "(Tensor) A tensor of shape [num_class, dim]. 'num_class' is the "
             "total number of class.");
    AddInput("Bias",
             "(Tensor) A tensor of shape [num_class]. 'num_class' is the total "
             "number of class. It is a dispensable input.")
        .AsDispensable();
    AddInput("SampleWeight",
             "(Tensor) A tensor of shape [batch_size] storing a weight for "
             "each sample. And it is a dispensable input. The default value of "
             "sample is 1.")
        .AsDispensable();
    AddOutput("Cost",
              "(Tensor) A tensor of shape [batch_size]. Cost of samples.");
    AddOutput("SampleLogits", "An intermediate tensor.").AsIntermediate();
    AddOutput("SampleLabels", "An intermediate tensor.").AsIntermediate();
    AddAttr<int>("num_classes", "Total number of classes.");
    AddAttr<int>("num_sampled_classes", "The number of negative classes.")
        .SetDefault(10);
    AddAttr<std::vector<int>>("sampled_labels", "");
W
wanghaoshuang 已提交
102
    AddComment(R"DOC(
W
wanghaoshuang 已提交
103 104 105 106
Computes and returns the noise-contrastive estimation training loss.
See [Noise-contrastive estimation: A new estimation principle for unnormalized statistical models](http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).
By default this uses a uniform distribution for sampling.
The number of target classes per example 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 已提交
107 108 109 110 111 112 113 114 115
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
W
wanghaoshuang 已提交
116 117 118 119 120 121
    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 已提交
122 123
                   "The input(Out@GRAD) should not be null");

W
wanghaoshuang 已提交
124 125
    auto x_dims = ctx->GetInputDim("Input");
    auto x_grad_name = framework::GradVarName("Input");
W
wanghaoshuang 已提交
126 127 128 129
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }

W
wanghaoshuang 已提交
130 131
    auto w_dims = ctx->GetInputDim("Weight");
    auto w_grad_name = framework::GradVarName("Weight");
W
wanghaoshuang 已提交
132 133 134 135
    if (ctx->HasOutput(w_grad_name)) {
      ctx->SetOutputDim(w_grad_name, w_dims);
    }

W
wanghaoshuang 已提交
136
    auto bias_grad_name = framework::GradVarName("Bias");
W
wanghaoshuang 已提交
137
    if (ctx->HasOutput(bias_grad_name)) {
W
wanghaoshuang 已提交
138
      auto bias_dims = ctx->GetInputDim("Bias");
W
wanghaoshuang 已提交
139 140 141
      ctx->SetOutputDim(bias_grad_name, bias_dims);
    }
  }
W
wanghaoshuang 已提交
142 143 144 145 146 147 148 149

 protected:
  framework::OpKernelType GetKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("Input")->type()),
        ctx.device_context());
  }
W
wanghaoshuang 已提交
150 151 152 153 154 155 156 157 158 159
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP(nce, ops::NCEOp, ops::NCEOpMaker, nce_grad, ops::NCEOpGrad);
REGISTER_OP_CPU_KERNEL(nce, ops::NCEKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(nce_grad,
                       ops::NCEGradKernel<paddle::platform::CPUPlace, float>);