softmax_with_cross_entropy_op.cc 10.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

C
caoying03 已提交
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. */
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/softmax_with_cross_entropy_op.h"
S
sneaxiy 已提交
16
#include <memory>
Z
Zeng Jinle 已提交
17 18 19
#include <string>
#include <unordered_map>
#include <vector>
Y
Yu Yang 已提交
20

21 22 23 24 25 26
namespace paddle {
namespace operators {

class SoftmaxWithCrossEntropyOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
27
  void Make() override {
C
caoying03 已提交
28
    AddInput("Logits",
29
             "(Tensor, default: Tensor<float>), The unscaled log probabilities "
C
caoying03 已提交
30
             "which is a 2-D tensor with shape [N x K]. N is the batch_size, "
31 32
             "and K is the class number.");
    AddInput("Label",
C
caoying03 已提交
33 34 35 36
             "(Tensor) The ground truth which is a 2-D tensor. If soft_label "
             "is set to false, Label is a Tensor<int64> with shape [N x 1]. If "
             "soft_label is set to true, Label is a Tensor<float/double> with "
             "shape [N x K].");
C
caoying03 已提交
37 38
    AddOutput(
        "Softmax",
39
        "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N x K]. "
C
caoying03 已提交
40 41
        "The outputs value of softmax activation by given the input batch, "
        "which will be used in backward calculation.")
C
caoying03 已提交
42
        .AsIntermediate();
C
caoying03 已提交
43
    AddOutput("Loss",
44
              "(Tensor, default: Tensor<float>), A 2-D tensor. The cross "
C
caoying03 已提交
45
              "entropy loss with shape [N x 1].");
C
caoying03 已提交
46
    AddAttr<bool>(
47
        "soft_label",
C
caoying03 已提交
48 49 50
        "(bool, default: false), A flag to indicate whether to interpretate "
        "the given labels as soft labels.")
        .SetDefault(false);
S
sneaxiy 已提交
51 52
    AddAttr<bool>(
        "numeric_stable_mode",
53
        "(bool, default: true), A flag to indicate whether to use more "
S
sneaxiy 已提交
54 55
        "numerically stable algorithm. This flag is only valid when "
        "soft_label is false and GPU is used.")
56
        .SetDefault(true);
57 58 59 60 61 62
    AddAttr<int>(
        "ignore_index",
        "(int, default -100), Specifies a target value that is ignored and"
        "does not contribute to the input gradient. Only valid if soft_label"
        "is set to False")
        .SetDefault(-100);
63
    AddComment(R"DOC(
64 65 66
Softmax With Cross Entropy Operator.

Cross entropy loss with softmax is used as the output layer extensively. This
67
operator computes the softmax normalized values for each row of the input
68
tensor, after which cross-entropy loss is computed. This provides a more
69 70
numerically stable gradient.

71 72 73
Because this operator performs a softmax on logits internally, it expects
unscaled logits. This operator should not be used with the output of
softmax operator since that would produce incorrect results.
74

C
caoying03 已提交
75
When the attribute soft_label is set false, this operators expects mutually
76 77
exclusive hard labels, each sample in a batch is in exactly one class with a
probability of 1.0. Each sample in the batch will have a single label.
78

79
The equation is as follows:
80

81
1) Hard label (one-hot label, so every sample has exactly one class)
82

83
$$Loss_j =  -\text{Logit}_{Label_j} +
84
\log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right),
85
j = 1,..., K$$
C
caoying03 已提交
86

87
2) Soft label (each sample can have a distribution over all classes)
C
caoying03 已提交
88

89
$$Loss_j =  -\sum_{i=0}^{K}\text{Label}_i \left(\text{Logit}_i -
90
\log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right)\right),
91
j = 1,...,K$$
C
caoying03 已提交
92 93

)DOC");
94 95 96 97 98 99 100
  }
};

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

101
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
qiaolongfei 已提交
102 103 104 105 106 107 108 109 110 111
    PADDLE_ENFORCE(ctx->HasInput("Logits"),
                   "Input(Logits) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");

    PADDLE_ENFORCE(ctx->HasOutput("Softmax"),
                   "Output(Softmax) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("Loss"), "Output(Loss) should be not null.");

    auto logits_dims = ctx->GetInputDim("Logits");
    auto labels_dims = ctx->GetInputDim("Label");
112 113

    int rank = logits_dims.size();
C
caoying03 已提交
114
    PADDLE_ENFORCE_EQ(
115 116
        rank, labels_dims.size(),
        "Input(logits) and Input(Label) shall have the same rank.");
P
phlrain 已提交
117 118
    bool check = ctx->IsRuntime() || (framework::product(logits_dims) > 0 &&
                                      framework::product(labels_dims) > 0);
119 120 121 122 123 124
    if (check) {
      PADDLE_ENFORCE_EQ(framework::slice_ddim(logits_dims, 0, rank - 1),
                        framework::slice_ddim(labels_dims, 0, rank - 1),
                        "Input(X) and Input(Label) shall have the same shape "
                        "except the last dimension.");
    }
125

126
    if (ctx->Attrs().Get<bool>("soft_label")) {
127 128 129 130 131
      if (check) {
        PADDLE_ENFORCE_EQ(logits_dims[rank - 1], labels_dims[rank - 1],
                          "If Attr(soft_label) == true, the last dimension of "
                          "Input(X) and Input(Label) should be equal.");
      }
132
    } else {
133 134
      PADDLE_ENFORCE_EQ(labels_dims[rank - 1], 1UL,
                        "If Attr(softLabel) == false, the last dimension of "
135 136 137
                        "Input(Label) should be 1.");
    }

Q
qiaolongfei 已提交
138
    ctx->SetOutputDim("Softmax", logits_dims);
139 140 141
    auto loss_dims = logits_dims;
    loss_dims[rank - 1] = 1;
    ctx->SetOutputDim("Loss", loss_dims);
142

Q
qiaolongfei 已提交
143 144
    ctx->ShareLoD("Logits", /*->*/ "Softmax");
    ctx->ShareLoD("Logits", /*->*/ "Loss");
C
caoying03 已提交
145
  }
Y
Yu Yang 已提交
146

147
 protected:
148
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
149
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
150 151
    return framework::OpKernelType(ctx.Input<Tensor>("Logits")->type(),
                                   ctx.device_context());
Y
Yu Yang 已提交
152
  }
C
caoying03 已提交
153 154 155 156 157 158
};

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

159
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
qiaolongfei 已提交
160 161 162 163 164 165 166 167 168 169
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")),
                   "Input(Loss@Grad) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Softmax"),
                   "Input(Softmax) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")),
                   "Output(Logits@Grad) should be not null.");

    auto softmax_dims = ctx->GetInputDim("Softmax");
    auto labels_dims = ctx->GetInputDim("Label");
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

    int rank = softmax_dims.size();
    PADDLE_ENFORCE_EQ(
        rank, labels_dims.size(),
        "Input(logits) and Input(Label) shall have the same rank.");
    bool check = true;
    if ((!ctx->IsRuntime()) && (framework::product(softmax_dims) <= 0 ||
                                framework::product(labels_dims) <= 0)) {
      check = false;
    }
    if (check) {
      PADDLE_ENFORCE_EQ(
          framework::slice_ddim(softmax_dims, 0, rank - 1),
          framework::slice_ddim(labels_dims, 0, rank - 1),
          "Input(Softmax) and Input(Label) shall have the same shape "
          "except the last dimension.");
    }
187

188
    if (ctx->Attrs().Get<bool>("soft_label")) {
189 190 191 192 193
      if (check) {
        PADDLE_ENFORCE_EQ(softmax_dims[rank - 1], labels_dims[rank - 1],
                          "If Attr(soft_label) == true, the last dimension of "
                          "Input( Softmax) and Input(Label) should be equal.");
      }
194
    } else {
195 196
      PADDLE_ENFORCE_EQ(labels_dims[rank - 1], 1UL,
                        "If Attr(softLabel) == false, the last dimension of "
197 198
                        "Input(Label) should be 1.");
    }
C
caoying03 已提交
199

Q
qiaolongfei 已提交
200 201
    ctx->SetOutputDim(framework::GradVarName("Logits"),
                      ctx->GetInputDim("Softmax"));
202
  }
Y
Yu Yang 已提交
203

204
 protected:
205
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
206
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
207
    return framework::OpKernelType(
Y
Yu Yang 已提交
208
        ctx.Input<Tensor>(framework::GradVarName("Loss"))->type(),
Y
Yu Yang 已提交
209
        ctx.device_context());
Y
Yu Yang 已提交
210
  }
211 212
};

213 214 215 216 217
class SoftmaxGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yu Yang 已提交
218 219
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* grad_op = new framework::OpDesc();
Y
Yu Yang 已提交
220 221 222 223 224 225 226
    grad_op->SetType("softmax_with_cross_entropy_grad");
    grad_op->SetInput("Label", Input("Label"));
    grad_op->SetInput("Softmax", Output("Softmax"));
    grad_op->SetInput(framework::GradVarName("Softmax"), OutputGrad("Softmax"));
    grad_op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss"));
    grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits"));
    grad_op->SetAttrMap(Attrs());
Y
Yu Yang 已提交
227
    return std::unique_ptr<framework::OpDesc>(grad_op);
228 229 230
  }
};

231 232 233 234 235 236 237 238 239 240 241 242 243
class SoftmaxWithCrossEntropyInplaceInference
    : public framework::InplaceOpInference {
 public:
  std::unordered_map<std::string, std::string> operator()(
      const framework::OpDesc& op_desc, bool use_cuda) const {
    if (use_cuda && !boost::get<bool>(op_desc.GetAttr("soft_label"))) {
      return {{"Logits", "Softmax"}};
    } else {
      return {};
    }
  }
};

Z
Zeng Jinle 已提交
244 245 246 247
class SoftmaxWithCrossEntropyGradInplaceInference
    : public framework::InplaceOpInference {
 public:
  std::unordered_map<std::string, std::string> operator()(
248
      const framework::OpDesc& op_desc, bool use_cuda) const {
Z
Zeng Jinle 已提交
249 250 251 252
    return {{"Softmax", framework::GradVarName("Logits")}};
  }
};

253 254 255 256 257
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

258
REGISTER_OPERATOR(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyOp,
259 260
                  ops::SoftmaxWithCrossEntropyOpMaker, ops::SoftmaxGradMaker,
                  ops::SoftmaxWithCrossEntropyInplaceInference);
261
REGISTER_OPERATOR(softmax_with_cross_entropy_grad,
Z
Zeng Jinle 已提交
262 263
                  ops::SoftmaxWithCrossEntropyOpGrad,
                  ops::SoftmaxWithCrossEntropyGradInplaceInference);
264
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy,
C
caoying03 已提交
265 266
                       ops::SoftmaxWithCrossEntropyKernel<float>,
                       ops::SoftmaxWithCrossEntropyKernel<double>);
267
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy_grad,
C
caoying03 已提交
268 269
                       ops::SoftmaxWithCrossEntropyGradKernel<float>,
                       ops::SoftmaxWithCrossEntropyGradKernel<double>);