kldiv_loss_op.cc 6.4 KB
Newer Older
D
dengkaipeng 已提交
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 27 28 29 30 31 32 33 34 35
/* Copyright (c) 2019 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/fluid/operators/kldiv_loss_op.h"
#include <string>
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

using framework::Tensor;

class KLDivLossOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of KLDivLossOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Target"),
                   "Input(Target) of KLDivLossOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Loss"),
                   "Output(Loss) of KLDivLossOp should not be null.");

    auto dim_x = ctx->GetInputDim("X");
    auto dim_target = ctx->GetInputDim("Target");
    PADDLE_ENFORCE_EQ(dim_x.size(), dim_target.size(),
                      "Input(X) rank and Input(Target) rank should be same.");
D
dengkaipeng 已提交
36
    for (int i = 0; i < dim_x.size(); i++) {
D
dengkaipeng 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
      PADDLE_ENFORCE_EQ(dim_x[i], dim_target[i],
                        "Input(X) and Input(Target) should in same shape.");
    }

    auto reduction = ctx->Attrs().Get<std::string>("reduction");

    PADDLE_ENFORCE(
        "mean" == reduction || "sum" == reduction || "batchmean" == reduction ||
            "none" == reduction,
        "Attr(reduction) can only be 'none'|'batchmean'|'sum'|'mean'.");

    if ("none" == reduction) {
      ctx->SetOutputDim("Loss", dim_x);
    } else {
      ctx->SetOutputDim("Loss", framework::make_ddim({1}));
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
                                   ctx.GetPlace());
  }
};

class KLDivLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input tensor of KL divergence loss operator, "
             "This is a tensor with shape of [N, *], where N is the"
             "batch size, * means any number of additional dimensions.");
    AddInput("Target",
             "The  tensor of KL divergence loss operator, "
             "This is a tensor with shape of Input(X).");
    AddOutput(
        "Loss",
        "The output KL divergence loss tensor. if Attr(reduction) is "
        "'none', this tensor should be in same shape of of Input(X), else "
        "this tensor should be in shape of [1].");

    AddAttr<std::string>(
        "reduction",
        "The reduction type to apply to the output, available types "
        "are 'none' | 'batchmean' | 'mean' | 'sum', 'none' for no "
        "reduction, 'batchmean' for the sum of output divided by "
D
dengkaipeng 已提交
84
        "batchmean size, 'mean' for the average valud of all output, "
D
dengkaipeng 已提交
85 86 87 88 89 90
        "'sum' for the sum of the output.")
        .SetDefault("mean");

    AddComment(R"DOC(
         This operator calculates the Kullback-Leibler divergence loss
         between Input(X) and Input(Target).
D
dengkaipeng 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

         KL divergence loss calculates as follows:

         $$l(x, y) = y * (\log y - x)$$

         While :attr:`reduction` is :attr:`none`, output loss is in
         same shape with Input(X), loss in each point is calculated 
         seperately and no reduction applied.
         
         While :attr:`reduction` is :attr:`mean`, output loss in in
         shape of [1] and loss value is the mean value of all losses.
         
         While :attr:`reduction` is :attr:`sum`, output loss in in
         shape of [1] and loss value is the sum value of all losses.
         
         While :attr:`reduction` is :attr:`batchmean`, output loss in 
         in shape of [1] and loss value is the sum value of all losses
         divided by batch size.
D
dengkaipeng 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
         
         )DOC");
  }
};

class KLDivLossOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
    PADDLE_ENFORCE(ctx->HasInput("Target"), "Input(Target) should not be null");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")),
                   "Input(Loss@GRAD) should not be null");
    auto dim_x = ctx->GetInputDim("X");
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"), dim_x);
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
                                   ctx.GetPlace());
  }
};

class KLDivLossOpGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* op = new framework::OpDesc();
    op->SetType("kldiv_loss_grad");
    op->SetInput("X", Input("X"));
    op->SetInput("Target", Input("Target"));
    op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss"));

    op->SetAttrMap(Attrs());

    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    return std::unique_ptr<framework::OpDesc>(op);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(kldiv_loss, ops::KLDivLossOp, ops::KLDivLossOpMaker,
                  ops::KLDivLossOpGradMaker);
REGISTER_OPERATOR(kldiv_loss_grad, ops::KLDivLossOpGrad);
REGISTER_OP_CPU_KERNEL(
    kldiv_loss, ops::KLDivLossKernel<paddle::platform::CPUDeviceContext, float>,
    ops::KLDivLossKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    kldiv_loss_grad,
    ops::KLDivLossGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::KLDivLossGradKernel<paddle::platform::CPUDeviceContext, double>);