sample_logits_op.cc 10.5 KB
Newer Older
X
xuezhong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 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. */
#include "paddle/fluid/operators/sample_logits_op.h"
15
#include <memory>
X
xuezhong 已提交
16 17 18 19 20 21 22 23 24 25 26 27
#include "paddle/fluid/operators/math/sample_prob.h"

namespace paddle {
namespace operators {

class SampleLogitsOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Logits",
             "(Tensor, default: Tensor<float>), The unscaled log probabilities "
             "which is a 2-D tensor with shape [N x K]. N is the batch_size, "
             "and K is the class number.");
X
xuezhong 已提交
28 29
    AddInput("Labels",
             "(Tensor) The ground truth which is a 2-D tensor. Labels is a "
X
xuezhong 已提交
30 31
             "Tensor<int64> with shape [N x NT], where NT is the number of"
             "true labels for each example.");
X
xuezhong 已提交
32 33 34 35 36 37 38 39 40
    AddInput("CustomizedSamples",
             "(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
             "NT + S],"
             " where N is the batch size, NT is the number of true labels "
             "and S is the number of negtive sample for each example."
             "The first NT elements of each row should be the same with true "
             "labels, "
             "followed by S custom negtive samples. This tensor"
             "is only used when use_customized_samples is true.")
X
xuezhong 已提交
41 42
        .AsDispensable();
    AddInput(
X
xuezhong 已提交
43 44 45 46 47 48
        "CustomizedProbabilities",
        "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
        "The tensor has the same shape with CustomSamples,"
        "and each element represents probability of element in CustomSamples. "
        "This "
        "tensor is only used when use_customized_samples is true.")
X
xuezhong 已提交
49
        .AsDispensable();
X
xuezhong 已提交
50 51 52 53 54 55 56
    AddOutput("Samples",
              "(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
              "NT + S]."
              "The outputs value of sampler, including NT true lables and S "
              "negetive samples "
              "for each example. This will be used in"
              "backward calculation.")
X
xuezhong 已提交
57 58 59
        .AsIntermediate();
    AddOutput(
        "Probabilities",
X
xuezhong 已提交
60 61
        "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
        "The probabilites of sampled positive and negtive labels.")
X
xuezhong 已提交
62
        .AsIntermediate();
63 64 65 66
    AddOutput("LogitsDim", "Store dim information of Logits for gradient op")
        .AsIntermediate();
    AddOutput("LabelsDim", "Store dim information of Logits for gradient op")
        .AsIntermediate();
X
xuezhong 已提交
67 68
    AddOutput("SampledLogits",
              "(Tensor, default: Tensor<float>), A 2-D tensor with shape"
X
xuezhong 已提交
69 70
              "[N, NT + S]. The outputs value of sampled logits, which will be"
              "used in backward propagation.")
X
xuezhong 已提交
71
        .AsIntermediate();
X
xuezhong 已提交
72
    AddOutput(
X
xuezhong 已提交
73 74 75
        "SampledLabels",
        "(Tensor, default: Tensor<int64>), A 2-D tensor. The sampled labels"
        "with shape [N, NT]. The tonsor contains hard labels as input to "
X
xuezhong 已提交
76
        " softmax op, that is 0, 1, ..., NT-1 because of the first NT elements"
X
xuezhong 已提交
77
        " of Sampels are positive lables.");
X
xuezhong 已提交
78
    AddAttr<bool>(
X
xuezhong 已提交
79 80 81 82
        "use_customized_samples",
        "An indicator whether to use customized samples with probabilities, if "
        "True"
        "the operator will use customized samples and customized probabilities"
X
xuezhong 已提交
83 84 85 86 87 88
        "otherwise, the operator will generate them by itself.")
        .SetDefault(false);
    AddAttr<bool>(
        "uniq",
        "An indicator whether to sample non-repetitive negtive labels, if True"
        "the operator will sample negtive labels without replacement."
X
xuezhong 已提交
89
        "Otherwise, the operator will sample negtive labels with replacement.")
X
xuezhong 已提交
90
        .SetDefault(true);
X
xuezhong 已提交
91 92 93 94 95 96 97 98 99 100
    AddAttr<bool>(
        "remove_accidental_hits",
        "An indicator whether to remove accidental hits when samples hits true"
        "labels, the removal is implemented by subtracting the corresponding"
        "logits by float_max to subpress their softmax to be zero.")
        .SetDefault(true);
    AddAttr<int>("num_samples", "The number of negative samples.");
    AddAttr<int>("seed", "Random seed for generating samples").SetDefault(0);

    AddComment(R"DOC(
X
xuezhong 已提交
101 102
  """
  Computes sampled output training logits and labels suitable for implementing
X
xuezhong 已提交
103
  sampled softmax.        
X
xuezhong 已提交
104
  """
X
xuezhong 已提交
105 106 107 108 109 110 111 112 113 114 115 116

)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Logits"),
                   "Input(Logits) should be not null.");
X
xuezhong 已提交
117 118
    PADDLE_ENFORCE(ctx->HasInput("Labels"),
                   "Input(Labels) should be not null.");
X
xuezhong 已提交
119 120 121 122 123 124 125

    PADDLE_ENFORCE(ctx->HasOutput("Samples"),
                   "Output(Samples) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("Probabilities"),
                   "Output(Probabilities) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("SampledLogits"),
                   "Output(SampledLogits) should be not null.");
X
xuezhong 已提交
126 127
    PADDLE_ENFORCE(ctx->HasOutput("SampledLabels"),
                   "Output(SampledLabels) should be not null.");
128 129 130 131
    PADDLE_ENFORCE(ctx->HasOutput("LogitsDim"),
                   "Output(LogitsDim) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("LabelsDim"),
                   "Output(LabelsDim) should be not null.");
X
xuezhong 已提交
132 133

    auto logits_dims = ctx->GetInputDim("Logits");
X
xuezhong 已提交
134
    auto labels_dims = ctx->GetInputDim("Labels");
X
xuezhong 已提交
135 136 137 138 139 140 141 142

    PADDLE_ENFORCE_EQ(
        logits_dims.size(), 2UL,
        "The logits of softmax_with_cross_entropy should be a 2-D tensor.");
    PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
                      "The labels should be a 2-D tensor.");

    const int num_samples = ctx->Attrs().Get<int>("num_samples");
X
xuezhong 已提交
143 144 145 146
    int num_sampled_classes = labels_dims[1] + num_samples;
    if ((!ctx->IsRuntime()) && labels_dims[1] <= 0) {
      num_sampled_classes = -1;
    }
X
xuezhong 已提交
147 148 149
    ctx->SetOutputDim("Samples", {logits_dims[0], num_sampled_classes});
    ctx->SetOutputDim("Probabilities", {logits_dims[0], num_sampled_classes});
    ctx->SetOutputDim("SampledLogits", {logits_dims[0], num_sampled_classes});
X
xuezhong 已提交
150
    ctx->SetOutputDim("SampledLabels", {logits_dims[0], labels_dims[1]});
151 152 153 154 155 156 157 158 159

    // append 0 to shape variable to avoid optimized by memory optimize pass
    auto logits_dim_vec = framework::vectorize(logits_dims);
    logits_dim_vec.push_back(0);
    ctx->SetOutputDim("LogitsDim", framework::make_ddim(logits_dim_vec));

    auto labels_dim_vec = framework::vectorize(labels_dims);
    labels_dim_vec.push_back(0);
    ctx->SetOutputDim("LabelsDim", framework::make_ddim(labels_dim_vec));
X
xuezhong 已提交
160 161 162 163 164
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
165
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Logits");
X
xuezhong 已提交
166 167 168 169 170 171 172 173 174 175 176 177
    framework::OpKernelType kt =
        framework::OpKernelType(data_type, ctx.device_context());
    return kt;
  }
};

// UNDERSTAND: InferShape for Grad
class SampleLogitsOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
178 179 180 181
    PADDLE_ENFORCE(ctx->HasInput("LogitsDim"),
                   "Input(LogitsDim) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("LabelsDim"),
                   "Input(LabelsDim) should be not null.");
X
xuezhong 已提交
182 183 184 185 186 187 188
    PADDLE_ENFORCE(ctx->HasInput("Samples"),
                   "Input(Samples) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("SampledLogits")),
                   "Input(SampledLogits@Grad) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")),
                   "Output(Logits@Grad) should be not null.");

189 190 191 192 193
    auto logits_dims = ctx->GetInputDim("LogitsDim");
    logits_dims = framework::DDim(logits_dims.Get(), logits_dims.size() - 1);
    auto labels_dims = ctx->GetInputDim("LabelsDim");
    labels_dims = framework::DDim(labels_dims.Get(), labels_dims.size() - 1);
    PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
X
xuezhong 已提交
194
                      "The label should be a 2-D tensor.");
195
    PADDLE_ENFORCE_EQ(logits_dims.size(), 2UL,
X
xuezhong 已提交
196 197
                      "The logits should be a 2-D tensor.");

198
    ctx->SetOutputDim(framework::GradVarName("Logits"), logits_dims);
X
xuezhong 已提交
199 200 201 202 203
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
204 205
    auto data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("SampledLogits"));
X
xuezhong 已提交
206 207 208 209 210 211 212
    framework::OpKernelType kt =
        framework::OpKernelType(data_type, ctx.device_context());
    return kt;
  }
};

// UNDERSTAND: what's the rule for making a GradMaker TODO
H
hong 已提交
213 214 215

template <typename T>
class SampleLogitsGradMaker : public framework::SingleGradOpMaker<T> {
X
xuezhong 已提交
216
 public:
H
hong 已提交
217
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
X
xuezhong 已提交
218 219

 protected:
H
hong 已提交
220 221
  std::unique_ptr<T> Apply() const override {
    auto* grad_op = new T();
X
xuezhong 已提交
222
    grad_op->SetType("sample_logits_grad");
H
hong 已提交
223 224 225
    grad_op->SetInput("LogitsDim", this->Output("LogitsDim"));
    grad_op->SetInput("LabelsDim", this->Output("LabelsDim"));
    grad_op->SetInput("Samples", this->Output("Samples"));
X
xuezhong 已提交
226
    grad_op->SetInput(framework::GradVarName("SampledLogits"),
H
hong 已提交
227 228 229 230 231
                      this->OutputGrad("SampledLogits"));
    grad_op->SetOutput(framework::GradVarName("Logits"),
                       this->InputGrad("Logits"));
    grad_op->SetAttrMap(this->Attrs());
    return std::unique_ptr<T>(grad_op);
X
xuezhong 已提交
232 233 234 235 236 237 238 239 240
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(sample_logits, ops::SampleLogitsOp, ops::SampleLogitsOpMaker,
H
hong 已提交
241 242
                  ops::SampleLogitsGradMaker<paddle::framework::OpDesc>,
                  ops::SampleLogitsGradMaker<paddle::imperative::OpBase>);
X
xuezhong 已提交
243 244 245 246 247
REGISTER_OPERATOR(sample_logits_grad, ops::SampleLogitsOpGrad);
REGISTER_OP_CPU_KERNEL(sample_logits, ops::SampleLogitsKernel<float>,
                       ops::SampleLogitsKernel<double>);
REGISTER_OP_CPU_KERNEL(sample_logits_grad, ops::SampleLogitsGradKernel<float>,
                       ops::SampleLogitsGradKernel<double>);