kldiv_loss_op.h 4.0 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
/* 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. */

#pragma once
#include <string>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/hostdevice.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using Array1 = Eigen::DSizes<int64_t, 1>;

template <typename T>
struct KLDivLossForward {
  HOSTDEVICE KLDivLossForward() {}

  HOSTDEVICE T operator()(const T& target, const T& input) const {
D
dengkaipeng 已提交
29
    if (target <= 0) {
D
dengkaipeng 已提交
30 31 32 33 34 35 36
      return 0;
    } else {
      return target * (std::log(target) - input);
    }
  }
};

D
dengkaipeng 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49
template <typename T>
struct KLDivLossBackward {
  HOSTDEVICE KLDivLossBackward() {}

  HOSTDEVICE T operator()(const T& target, const T& grad) const {
    if (target <= 0) {
      return 0;
    } else {
      return static_cast<T>(-1.) * grad;
    }
  }
};

D
dengkaipeng 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62
template <typename DeviceContext, typename T>
class KLDivLossKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto* input = ctx.Input<Tensor>("X");
    auto* target = ctx.Input<Tensor>("Target");
    auto* loss = ctx.Output<Tensor>("Loss");
    auto reduction = ctx.Attr<std::string>("reduction");

    const int n = input->dims()[0];

    loss->mutable_data<T>(ctx.GetPlace());
W
wuhuanzhou 已提交
63 64 65
    auto input_t = framework::EigenVector<T>::Flatten(*input);
    auto target_t = framework::EigenVector<T>::Flatten(*target);
    auto loss_t = framework::EigenVector<T>::Flatten(*loss);
D
dengkaipeng 已提交
66 67 68 69
    auto output = target_t.binaryExpr(input_t, KLDivLossForward<T>());
    if ("none" == reduction) {
      loss_t.device(place) = output;
    } else if ("batchmean" == reduction) {
70
      auto output_sum = output.sum();
L
LielinJiang 已提交
71 72 73 74 75
      if (n > 0) {
        loss_t.device(place) = output_sum / output_sum.constant(n);
      } else {
        loss_t.device(place) = output_sum;
      }
D
dengkaipeng 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    } else if ("mean" == reduction) {
      loss_t.device(place) = output.mean();
    } else if ("sum" == reduction) {
      loss_t.device(place) = output.sum();
    }
  }
};

template <typename DeviceContext, typename T>
class KLDivLossGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto* target = ctx.Input<Tensor>("Target");
    auto reduction = ctx.Attr<std::string>("reduction");
    auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* loss_grad = ctx.Input<Tensor>(framework::GradVarName("Loss"));

D
dengkaipeng 已提交
94 95
    const int n = input_grad->dims()[0];
    const int numel = input_grad->numel();
D
dengkaipeng 已提交
96 97 98 99
    const int expand = numel / loss_grad->numel();

    input_grad->mutable_data<T>(ctx.GetPlace());

W
wuhuanzhou 已提交
100
    auto target_t = framework::EigenVector<T>::Flatten(*target);
D
dengkaipeng 已提交
101

W
wuhuanzhou 已提交
102 103
    auto input_grad_t = framework::EigenVector<T>::Flatten(*input_grad);
    auto loss_grad_t = framework::EigenVector<T>::Flatten(*loss_grad);
D
dengkaipeng 已提交
104 105

    auto loss_grad_expand = loss_grad_t.broadcast(Array1(expand));
D
dengkaipeng 已提交
106
    auto grad_t = target_t * loss_grad_expand;
D
dengkaipeng 已提交
107 108
    input_grad_t.device(place) =
        target_t.binaryExpr(grad_t, KLDivLossBackward<T>());
D
dengkaipeng 已提交
109 110 111 112 113 114 115 116 117 118 119

    if ("mean" == reduction) {
      input_grad_t.device(place) = input_grad_t / static_cast<T>(numel);
    } else if ("batchmean" == reduction) {
      input_grad_t.device(place) = input_grad_t / static_cast<T>(n);
    }
  }
};

}  // namespace operators
}  // namespace paddle