cross_entropy_op.cc 16.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Q
Qiao Longfei 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

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

S
sneaxiy 已提交
17
#include <memory>
C
chengduo 已提交
18
#include <string>
19
#include <unordered_map>
Q
Qiao Longfei 已提交
20 21 22 23

namespace paddle {
namespace operators {

S
sneaxiy 已提交
24
class CrossEntropyOpBase : public framework::OperatorWithKernel {
S
sneaxiy 已提交
25 26 27 28
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
29 30 31
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "CrossEntropy");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "CrossEntropy");
    OP_INOUT_CHECK(ctx->HasOutput("Y"), "Output", "Y", "CrossEntropy");
S
sneaxiy 已提交
32 33 34 35

    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
    int rank = x_dims.size();
36

37 38
    bool contain_unknown_dim = phi::contain_unknown_dim(x_dims) ||
                               phi::contain_unknown_dim(label_dims);
H
Hongyu Liu 已提交
39
    bool check = ctx->IsRuntime() || !contain_unknown_dim;
40

S
sneaxiy 已提交
41
    if (check) {
42
      PADDLE_ENFORCE_EQ(
43 44
          phi::slice_ddim(x_dims, 0, rank - 1),
          phi::slice_ddim(label_dims, 0, rank - 1),
45 46 47 48 49
          platform::errors::InvalidArgument(
              "Input(X) and Input(Label) shall have the same shape "
              "except the last dimension. But received: the shape of Input(X) "
              "is "
              "[%s], the shape of Input(Label) is [%s].",
50 51
              x_dims,
              label_dims));
S
sneaxiy 已提交
52
    }
S
sneaxiy 已提交
53 54

    if (IsSoftLabel(ctx)) {
55
      PADDLE_ENFORCE_EQ(
56 57
          rank,
          label_dims.size(),
58 59 60 61 62 63 64 65
          platform::errors::InvalidArgument(
              "If Attr(soft_label) == true, Input(X) and Input(Label) "
              "shall have the same dimensions. But received: the dimensions of "
              "Input(X) is [%d],"
              "the shape of Input(X) is [%s], the dimensions of Input(Label) "
              "is "
              "[%d], the shape of"
              "Input(Label) is [%s]",
66 67 68 69
              rank,
              x_dims,
              label_dims.size(),
              label_dims));
70

S
sneaxiy 已提交
71
      if (check) {
72
        PADDLE_ENFORCE_EQ(
73 74
            x_dims[rank - 1],
            label_dims[rank - 1],
75 76 77 78 79 80 81 82
            platform::errors::InvalidArgument(
                "If Attr(soft_label) == true, the last dimension of "
                "Input(X) and Input(Label) should be equal. But received: the"
                "last dimension of Input(X) is [%d], the shape of Input(X) is "
                "[%s],"
                "the last dimension of Input(Label) is [%d], the shape of "
                "Input(Label)"
                "is [%s], the last dimension is [%d].",
83 84 85 86
                x_dims[rank - 1],
                x_dims,
                label_dims[rank - 1],
                label_dims,
87
                rank - 1));
S
sneaxiy 已提交
88 89
      }
    } else {
90 91
      if (rank == label_dims.size()) {
        PADDLE_ENFORCE_EQ(
92 93
            label_dims[rank - 1],
            1UL,
94 95 96 97
            platform::errors::InvalidArgument(
                "the last dimension of Input(Label) should be 1."
                "But received: the last dimension of Input(Label) is [%d],"
                "the last dimension is [%d]",
98 99
                label_dims[rank - 1],
                rank - 1));
100
      } else {
101
        PADDLE_ENFORCE_EQ(
102 103
            rank,
            label_dims.size() + 1,
104 105 106 107 108 109 110
            platform::errors::InvalidArgument(
                "ShapeError: The rank of Input(X) should be equal to "
                "Input(Label) plus 1."
                "But received: The dimension of Input(X) is [%d], "
                "the shape of Input(X) is [%s],"
                "the dimension of Input(Label) is [%d], the shape of "
                "Input(Label) is [%s]",
111 112 113 114
                rank,
                x_dims,
                label_dims.size(),
                label_dims));
115
      }
S
sneaxiy 已提交
116 117
    }

118 119 120 121
    auto y_dims = label_dims;
    if (rank == label_dims.size()) {
      y_dims[rank - 1] = 1;
    }
S
sneaxiy 已提交
122 123 124 125 126 127 128 129 130
    ctx->SetOutputDim("Y", y_dims);
    ctx->ShareLoD("X", /*->*/ "Y");
  }

 protected:
  // Explicitly set that the data type of computation kernel of cross_entropy
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
131 132 133
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
S
sneaxiy 已提交
134
  }
S
sneaxiy 已提交
135 136 137 138

  virtual bool IsSoftLabel(framework::InferShapeContext* ctx) const {
    return ctx->Attrs().Get<bool>("soft_label");
  }
S
sneaxiy 已提交
139 140
};

S
sneaxiy 已提交
141
class CrossEntropyGradientOpBase : public framework::OperatorWithKernel {
S
sneaxiy 已提交
142 143 144
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

S
sneaxiy 已提交
145
  void InferShape(framework::InferShapeContext* ctx) const {
146 147 148 149 150 151 152 153 154
    OP_INOUT_CHECK(
        ctx->HasInput("Label"), "Input", "Label", "CrossEntropyGradientOpBase");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")),
                   "Input",
                   framework::GradVarName("Y"),
                   "CrossEntropyGradientOpBase");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   framework::GradVarName("X"),
155
                   "CrossEntropyGradientOpBase");
S
sneaxiy 已提交
156

S
sneaxiy 已提交
157
    auto x_dims = GetXDim(ctx);
S
sneaxiy 已提交
158 159 160
    auto label_dims = ctx->GetInputDim("Label");
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
    int rank = x_dims.size();
161
    PADDLE_ENFORCE_EQ(
162 163
        dy_dims.size(),
        label_dims.size(),
164 165 166
        platform::errors::InvalidArgument(
            "Input(Y@Grad) and Input(Y) should have the same rank."
            "But received: Y@Grad's rank is [%d], Y's rank is [%d]",
167 168
            dy_dims.size(),
            label_dims.size()));
S
sneaxiy 已提交
169

170
    bool contain_unknown_dim =
171
        phi::contain_unknown_dim(x_dims) || phi::contain_unknown_dim(dy_dims);
172 173

    bool check = ctx->IsRuntime() || !contain_unknown_dim;
S
sneaxiy 已提交
174 175

    if (check) {
176
      PADDLE_ENFORCE_EQ(
177 178
          phi::slice_ddim(x_dims, 0, rank - 1),
          phi::slice_ddim(dy_dims, 0, rank - 1),
179 180 181 182 183
          platform::errors::InvalidArgument(
              "The Input(X) and Input(Y@Grad) should have the same "
              "shape except the last dimension. but received: "
              "the shape of Input(X) is [%s], "
              "the shape of Input(Y@Grad) is [%s].",
184 185
              x_dims,
              dy_dims));
S
sneaxiy 已提交
186
    }
187

S
sneaxiy 已提交
188 189
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    ctx->ShareLoD(VarNameWithXLoD(), framework::GradVarName("X"));
S
sneaxiy 已提交
190 191 192 193 194 195 196
  }

 protected:
  // Explicitly set that the data type of computation kernel of cross_entropy
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
197 198 199
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Y")),
                                   ctx.device_context());
S
sneaxiy 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  }

  virtual framework::DDim GetXDim(framework::InferShapeContext* ctx) const {
    return ctx->GetInputDim("X");
  }

  virtual const char* VarNameWithXLoD() const { return "X"; }

  virtual bool IsSoftLabel(framework::InferShapeContext* ctx) const {
    return ctx->Attrs().Get<bool>("soft_label");
  }
};

class CrossEntropyOpInferVarType
    : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
216
  std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
S
sneaxiy 已提交
217
      const override {
218 219
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Y"}};
    return m;
S
sneaxiy 已提交
220 221 222
  }
};

223
class CrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker {
224
 public:
Y
Yu Yang 已提交
225
  void Make() override {
C
caoying03 已提交
226
    AddInput("X",
F
stash  
fengjiayi 已提交
227 228 229 230 231 232 233 234 235 236
             "(Tensor, default Tensor<float>), a tensor whose last dimension "
             "size is equal to the number of classes. This input is a "
             "probability computed by the previous operator, which is almost "
             "always the result of a softmax operator.");
    AddInput(
        "Label",
        "(Tensor), the tensor which represents the ground truth. It has the "
        "same shape with 'X' except the last dimension. When soft_label is set "
        "to false, the last dimension size is 1; when soft_label is set to "
        "true, the last dimension size is equal to the number of classes.");
C
caoying03 已提交
237
    AddOutput("Y",
F
stash  
fengjiayi 已提交
238 239 240
              "(Tensor, default Tensor<float>), a tensor whose shape is same "
              "with 'X' except that the last dimension size is 1. It "
              "represents the cross entropy loss.");
C
caoying03 已提交
241 242
    AddAttr<bool>("soft_label",
                  "(bool, default false), a flag indicating whether to "
T
tianshuo78520a 已提交
243
                  "interpretant the given labels as soft labels.")
244
        .SetDefault(false);
245 246 247 248 249
    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);
Q
Qiao Longfei 已提交
250
    AddComment(R"DOC(
251
CrossEntropy Operator.
Q
Qiao Longfei 已提交
252

F
stash  
fengjiayi 已提交
253 254 255 256 257 258
The input 'X' and 'Label' will first be logically flattened to 2-D matrixs. 
The matrix's second dimension(row length) is as same as the original last 
dimension, and the first dimension(column length) is the product of all other 
original dimensions. Then the softmax computation will take palce on each raw 
of flattened matrixs.

259 260 261
It supports both standard cross-entropy and soft-label cross-entropy loss
computation.
1) One-hot cross-entropy:
262
    soft_label = false, Label[i, 0] indicates the class index for sample i:
263

K
Kexin Zhao 已提交
264
                $Y[i] = -\log(X[i, Label[i]])$
Q
Qiao Longfei 已提交
265

266
2) Soft-label cross-entropy:
267
    soft_label = true, Label[i, j] indicates the soft label of class j
268
    for sample i:
269

K
Kexin Zhao 已提交
270
                $Y[i] = \sum_j{-Label[i, j] * log(X[i, j])}$
271

272
   Please make sure that in this case the summuation of each row of Label
273 274 275 276 277 278
   equals one.

3) One-hot cross-entropy with vecterized Input(Label):
     As a special case of 2), when each row of Input(Label) has only one
     non-zero element (equals 1), soft-label cross-entropy degenerates to a
     one-hot cross-entropy with one-hot label representation.
D
dangqingqing 已提交
279

K
Kexin Zhao 已提交
280 281 282
Both the input X and Label can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input X.

Q
Qiao Longfei 已提交
283 284 285
)DOC");
  }
};
C
chengduo 已提交
286

S
sneaxiy 已提交
287 288 289 290 291
class CrossEntropyGradientOp : public CrossEntropyGradientOpBase {
 public:
  using CrossEntropyGradientOpBase::CrossEntropyGradientOpBase;

  void InferShape(framework::InferShapeContext* ctx) const override {
292
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "CrossEntropyGradientOp");
S
sneaxiy 已提交
293 294 295 296
    CrossEntropyGradientOpBase::InferShape(ctx);
  }
};

H
hong 已提交
297 298
template <typename T>
class CrossEntropyGradOpMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
299
 public:
H
hong 已提交
300
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
301 302

 protected:
303
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
304
    op->SetType("cross_entropy_grad");
H
hong 已提交
305 306 307 308 309
    op->SetInput("X", this->Input("X"));
    op->SetInput("Label", this->Input("Label"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
310 311 312
  }
};

S
sneaxiy 已提交
313 314 315 316 317 318 319
class CrossEntropyOp2 : public CrossEntropyOpBase {
 public:
  using CrossEntropyOpBase::CrossEntropyOpBase;

  void InferShape(framework::InferShapeContext* ctx) const override {
    CrossEntropyOpBase::InferShape(ctx);

320 321 322 323
    OP_INOUT_CHECK(
        ctx->HasOutput("XShape"), "Output", "XShape", "CrossEntropyOp2");
    OP_INOUT_CHECK(
        ctx->HasOutput("MatchX"), "Output", "MatchX", "CrossEntropyOp2");
S
sneaxiy 已提交
324
    auto x_dims = ctx->GetInputDim("X");
325
    auto x_dims_vec = phi::vectorize(x_dims);
S
sneaxiy 已提交
326
    x_dims_vec.push_back(0);
327
    ctx->SetOutputDim("XShape", phi::make_ddim(x_dims_vec));
S
sneaxiy 已提交
328 329
    x_dims[x_dims.size() - 1] = 1;
    ctx->SetOutputDim("MatchX", x_dims);
S
sneaxiy 已提交
330 331 332
    ctx->ShareLoD("X", /*->*/ "XShape");
  }

S
sneaxiy 已提交
333
 protected:
S
sneaxiy 已提交
334 335 336 337 338 339 340 341
  bool IsSoftLabel(framework::InferShapeContext* ctx) const override {
    return false;
  }
};

class CrossEntropyGradientOp2 : public CrossEntropyGradientOpBase {
 public:
  using CrossEntropyGradientOpBase::CrossEntropyGradientOpBase;
S
sneaxiy 已提交
342
  void InferShape(framework::InferShapeContext* ctx) const override {
343 344
    OP_INOUT_CHECK(
        ctx->HasInput("MatchX"), "Input", "MatchX", "CrossEntropyGradientOp2");
S
sneaxiy 已提交
345 346
    CrossEntropyGradientOpBase::InferShape(ctx);
  }
S
sneaxiy 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

 protected:
  virtual framework::DDim GetXDim(framework::InferShapeContext* ctx) const {
    auto x_shape = ctx->GetInputDim("XShape");
    return framework::DDim(x_shape.Get(), x_shape.size() - 1);
  }

  virtual const char* VarNameWithXLoD() const { return "XShape"; }

  virtual bool IsSoftLabel(framework::InferShapeContext* ctx) const {
    return false;
  }
};

class CrossEntropyOpMaker2 : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensor, default Tensor<float>), a tensor whose last dimension "
             "size is equal to the number of classes. This input is a "
             "probability computed by the previous operator, which is almost "
             "always the result of a softmax operator.");
    AddInput(
        "Label",
        "(Tensor), the tensor which represents the ground truth. It has the "
        "same shape with 'X' except the last dimension. One hot Tensor.");
    AddOutput("Y",
              "(Tensor, default Tensor<float>), a tensor whose shape is same "
              "with 'X' except that the last dimension size is 1. It "
              "represents the cross entropy loss.");
    AddOutput("XShape", "Temporaily variable to save shape and LoD of X.");
S
sneaxiy 已提交
378 379
    AddOutput("MatchX",
              "X value that matches label, used for gradient computation.");
S
sneaxiy 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    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);
    AddComment(R"DOC(
Hard-label CrossEntropy Operator.

The input 'X' and 'Label' will first be logically flattened to 2-D matrixs. 
The matrix's second dimension(row length) is as same as the original last 
dimension, and the first dimension(column length) is the product of all other 
original dimensions. Then the softmax computation will take palce on each raw 
of flattened matrixs.

Only support hard label.

Both the input X and Label can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input X.

)DOC");
  }
};

H
hong 已提交
403 404
template <typename T>
class CrossEntropyGradOpMaker2 : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
405
 public:
H
hong 已提交
406
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
407 408

 protected:
409
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
410
    op->SetType("cross_entropy_grad2");
H
hong 已提交
411 412 413 414 415 416
    op->SetInput("Label", this->Input("Label"));
    op->SetInput("MatchX", this->Output("MatchX"));
    op->SetInput("XShape", this->Output("XShape"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
417 418
  }
};
S
sneaxiy 已提交
419

Q
Qiao Longfei 已提交
420 421 422
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
423
namespace ops = paddle::operators;
L
Leo Chen 已提交
424
using CPUCtx = phi::CPUContext;
425

426 427 428 429
REGISTER_OPERATOR(cross_entropy,
                  ops::CrossEntropyOpBase,
                  ops::CrossEntropyOpMaker,
                  ops::CrossEntropyOpInferVarType,
H
hong 已提交
430 431
                  ops::CrossEntropyGradOpMaker<paddle::framework::OpDesc>,
                  ops::CrossEntropyGradOpMaker<paddle::imperative::OpBase>);
432
REGISTER_OPERATOR(cross_entropy_grad, ops::CrossEntropyGradientOp);
433 434
REGISTER_OP_CPU_KERNEL(cross_entropy,
                       ops::CrossEntropyOpKernel<CPUCtx, float>,
435
                       ops::CrossEntropyOpKernel<CPUCtx, double>);
436
REGISTER_OP_CPU_KERNEL(cross_entropy_grad,
437 438
                       ops::CrossEntropyGradientOpKernel<CPUCtx, float>,
                       ops::CrossEntropyGradientOpKernel<CPUCtx, double>);
S
sneaxiy 已提交
439

440 441 442 443
REGISTER_OPERATOR(cross_entropy2,
                  ops::CrossEntropyOp2,
                  ops::CrossEntropyOpMaker2,
                  ops::CrossEntropyOpInferVarType,
H
hong 已提交
444 445
                  ops::CrossEntropyGradOpMaker2<paddle::framework::OpDesc>,
                  ops::CrossEntropyGradOpMaker2<paddle::imperative::OpBase>);
S
sneaxiy 已提交
446 447 448 449 450 451 452
REGISTER_OPERATOR(cross_entropy_grad2, ops::CrossEntropyGradientOp2);
REGISTER_OP_CPU_KERNEL(cross_entropy2,
                       ops::CrossEntropyOpKernel2<CPUCtx, float>,
                       ops::CrossEntropyOpKernel2<CPUCtx, double>);
REGISTER_OP_CPU_KERNEL(cross_entropy_grad2,
                       ops::CrossEntropyGradientOpKernel2<CPUCtx, float>,
                       ops::CrossEntropyGradientOpKernel2<CPUCtx, double>);