|
| 1 | +/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. |
| 2 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | + you may not use this file except in compliance with the License. |
| 4 | + You may obtain a copy of the License at |
| 5 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + Unless required by applicable law or agreed to in writing, software |
| 7 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | + See the License for the specific language governing permissions and |
| 10 | + limitations under the License. */ |
| 11 | + |
| 12 | +#include "paddle/fluid/operators/kldiv_loss_op.h" |
| 13 | +#include <memory> |
| 14 | +#include <string> |
| 15 | +#include "paddle/fluid/framework/op_registry.h" |
| 16 | + |
| 17 | +namespace paddle { |
| 18 | +namespace operators { |
| 19 | + |
| 20 | +using framework::Tensor; |
| 21 | + |
| 22 | +class KLDivLossOp : public framework::OperatorWithKernel { |
| 23 | + public: |
| 24 | + using framework::OperatorWithKernel::OperatorWithKernel; |
| 25 | + void InferShape(framework::InferShapeContext* ctx) const override { |
| 26 | + PADDLE_ENFORCE(ctx->HasInput("X"), |
| 27 | + "Input(X) of KLDivLossOp should not be null."); |
| 28 | + PADDLE_ENFORCE(ctx->HasInput("Target"), |
| 29 | + "Input(Target) of KLDivLossOp should not be null."); |
| 30 | + PADDLE_ENFORCE(ctx->HasOutput("Loss"), |
| 31 | + "Output(Loss) of KLDivLossOp should not be null."); |
| 32 | + |
| 33 | + auto dim_x = ctx->GetInputDim("X"); |
| 34 | + auto dim_target = ctx->GetInputDim("Target"); |
| 35 | + PADDLE_ENFORCE_EQ(dim_x.size(), dim_target.size(), |
| 36 | + "Input(X) rank and Input(Target) rank should be same."); |
| 37 | + for (int i = 0; i < dim_x.size(); i++) { |
| 38 | + PADDLE_ENFORCE_EQ(dim_x[i], dim_target[i], |
| 39 | + "Input(X) and Input(Target) should in same shape."); |
| 40 | + } |
| 41 | + |
| 42 | + auto reduction = ctx->Attrs().Get<std::string>("reduction"); |
| 43 | + |
| 44 | + PADDLE_ENFORCE( |
| 45 | + "mean" == reduction || "sum" == reduction || "batchmean" == reduction || |
| 46 | + "none" == reduction, |
| 47 | + "Attr(reduction) can only be 'none'|'batchmean'|'sum'|'mean'."); |
| 48 | + |
| 49 | + if ("none" == reduction) { |
| 50 | + ctx->SetOutputDim("Loss", dim_x); |
| 51 | + } else { |
| 52 | + ctx->SetOutputDim("Loss", {1}); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + protected: |
| 57 | + framework::OpKernelType GetExpectedKernelType( |
| 58 | + const framework::ExecutionContext& ctx) const override { |
| 59 | + return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), |
| 60 | + ctx.GetPlace()); |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +class KLDivLossOpMaker : public framework::OpProtoAndCheckerMaker { |
| 65 | + public: |
| 66 | + void Make() override { |
| 67 | + AddInput("X", |
| 68 | + "The input tensor of KL divergence loss operator. " |
| 69 | + "This is a tensor with shape of [N, *], where N is the " |
| 70 | + "batch size, * means any number of additional dimensions."); |
| 71 | + AddInput("Target", |
| 72 | + "The tensor of KL divergence loss operator. " |
| 73 | + "This is a tensor with shape of Input(X)."); |
| 74 | + AddOutput( |
| 75 | + "Loss", |
| 76 | + "The output KL divergence loss tensor. if Attr(reduction) is " |
| 77 | + "'none', this tensor should be in same shape of of Input(X), else " |
| 78 | + "this tensor should be in shape of [1]."); |
| 79 | + |
| 80 | + AddAttr<std::string>( |
| 81 | + "reduction", |
| 82 | + "The reduction type to apply to the output, available types " |
| 83 | + "are 'none' | 'batchmean' | 'mean' | 'sum', 'none' for no " |
| 84 | + "reduction, 'batchmean' for the sum of output divided by " |
| 85 | + "batch size, 'mean' for the average value of all output, " |
| 86 | + "'sum' for the sum of the output.") |
| 87 | + .SetDefault("mean"); |
| 88 | + |
| 89 | + AddComment(R"DOC( |
| 90 | + This operator calculates the Kullback-Leibler divergence loss |
| 91 | + between Input(X) and Input(Target). |
| 92 | +
|
| 93 | + KL divergence loss is calculated as follows: |
| 94 | +
|
| 95 | + $$l(x, y) = y * (\log(y) - x)$$ |
| 96 | +
|
| 97 | + While :math:`x` is Input(X) and :math:`y` is Input(Target). |
| 98 | +
|
| 99 | + While :attr:`reduction` is :attr:`none`, output loss is in |
| 100 | + the same shape as Input(X), loss in each point is calculated |
| 101 | + seperately and no reduction is applied. |
| 102 | + |
| 103 | + While :attr:`reduction` is :attr:`mean`, output loss is in |
| 104 | + shape of [1] and loss value is the mean value of all losses. |
| 105 | + |
| 106 | + While :attr:`reduction` is :attr:`sum`, output loss is in |
| 107 | + shape of [1] and loss value is the sum value of all losses. |
| 108 | + |
| 109 | + While :attr:`reduction` is :attr:`batchmean`, output loss is |
| 110 | + in shape of [1] and loss value is the sum value of all losses |
| 111 | + divided by batch size. |
| 112 | + |
| 113 | + )DOC"); |
| 114 | + } |
| 115 | +}; |
| 116 | + |
| 117 | +class KLDivLossOpGrad : public framework::OperatorWithKernel { |
| 118 | + public: |
| 119 | + using framework::OperatorWithKernel::OperatorWithKernel; |
| 120 | + void InferShape(framework::InferShapeContext* ctx) const override { |
| 121 | + PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null"); |
| 122 | + PADDLE_ENFORCE(ctx->HasInput("Target"), "Input(Target) should not be null"); |
| 123 | + PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")), |
| 124 | + "Input(Loss@GRAD) should not be null"); |
| 125 | + auto dim_x = ctx->GetInputDim("X"); |
| 126 | + if (ctx->HasOutput(framework::GradVarName("X"))) { |
| 127 | + ctx->SetOutputDim(framework::GradVarName("X"), dim_x); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + protected: |
| 132 | + framework::OpKernelType GetExpectedKernelType( |
| 133 | + const framework::ExecutionContext& ctx) const override { |
| 134 | + return framework::OpKernelType(ctx.Input<Tensor>("X")->type(), |
| 135 | + ctx.GetPlace()); |
| 136 | + } |
| 137 | +}; |
| 138 | + |
| 139 | +class KLDivLossOpGradMaker : public framework::SingleGradOpDescMaker { |
| 140 | + public: |
| 141 | + using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; |
| 142 | + |
| 143 | + protected: |
| 144 | + std::unique_ptr<framework::OpDesc> Apply() const override { |
| 145 | + auto* op = new framework::OpDesc(); |
| 146 | + op->SetType("kldiv_loss_grad"); |
| 147 | + op->SetInput("X", Input("X")); |
| 148 | + op->SetInput("Target", Input("Target")); |
| 149 | + op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss")); |
| 150 | + |
| 151 | + op->SetAttrMap(Attrs()); |
| 152 | + |
| 153 | + op->SetOutput(framework::GradVarName("X"), InputGrad("X")); |
| 154 | + return std::unique_ptr<framework::OpDesc>(op); |
| 155 | + } |
| 156 | +}; |
| 157 | + |
| 158 | +} // namespace operators |
| 159 | +} // namespace paddle |
| 160 | + |
| 161 | +namespace ops = paddle::operators; |
| 162 | +REGISTER_OPERATOR(kldiv_loss, ops::KLDivLossOp, ops::KLDivLossOpMaker, |
| 163 | + ops::KLDivLossOpGradMaker); |
| 164 | +REGISTER_OPERATOR(kldiv_loss_grad, ops::KLDivLossOpGrad); |
| 165 | +REGISTER_OP_CPU_KERNEL( |
| 166 | + kldiv_loss, ops::KLDivLossKernel<paddle::platform::CPUDeviceContext, float>, |
| 167 | + ops::KLDivLossKernel<paddle::platform::CPUDeviceContext, double>); |
| 168 | +REGISTER_OP_CPU_KERNEL( |
| 169 | + kldiv_loss_grad, |
| 170 | + ops::KLDivLossGradKernel<paddle::platform::CPUDeviceContext, float>, |
| 171 | + ops::KLDivLossGradKernel<paddle::platform::CPUDeviceContext, double>); |
0 commit comments