cross_entropy_op.h 4.2 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 15

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
Y
Yi Wang 已提交
16 17 18 19
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/cross_entropy.h"
#include "paddle/fluid/operators/math/math_function.h"
20
#include "paddle/fluid/platform/for_range.h"
Q
Qiao Longfei 已提交
21 22 23 24

namespace paddle {
namespace operators {

D
dongzhihong 已提交
25 26
using Tensor = framework::Tensor;

27
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
28
class CrossEntropyOpKernel : public framework::OpKernel<T> {
29
 public:
D
dongzhihong 已提交
30
  void Compute(const framework::ExecutionContext& ctx) const override {
31 32 33
    auto* x = ctx.Input<Tensor>("X");
    auto* labels = ctx.Input<Tensor>("Label");
    auto* y = ctx.Output<Tensor>("Y");
34
    y->mutable_data<T>(ctx.GetPlace());
C
caoying03 已提交
35

36 37
    math::CrossEntropyFunctor<DeviceContext, T>()(
        ctx.template device_context<DeviceContext>(), y, x, labels,
Q
QI JUN 已提交
38
        ctx.Attr<bool>("soft_label"));
Y
Yan Chunwei 已提交
39 40 41
  }
};

42
template <typename T>
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 84 85 86 87 88 89 90 91 92 93
class XeSoftlabelGradFunctor {
 public:
  XeSoftlabelGradFunctor(T* dx,
                         const T* dy,     // NOLINT
                         const T* x,      // NOLINT
                         const T* label,  // NOLINT
                         size_t num_classes)
      : dx_(dx), dy_(dy), x_(x), label_(label), num_classes_(num_classes) {}

  HOSTDEVICE void operator()(size_t i) {
    auto row_ids = i / num_classes_;
    dx_[i] = -label_[i] * dy_[row_ids] / x_[i];
  }

 private:
  T* dx_;
  const T* dy_;
  const T* x_;
  const T* label_;
  size_t num_classes_;
};

template <typename T>
class XeGradFunctor {
 public:
  XeGradFunctor(T* dx,
                const T* dy,           // NOLINT
                const T* x,            // NOLINT
                const int64_t* label,  // NOLINT
                size_t num_classes)
      : dx_(dx), dy_(dy), x_(x), label_(label), num_classes_(num_classes) {}

  HOSTDEVICE void operator()(size_t label_id) {
    auto x_is_true_offset = label_id * num_classes_ + label_[label_id];
    for (size_t x_offset = label_id * num_classes_;
         x_offset < (label_id + 1) * num_classes_; ++x_offset) {
      dx_[x_offset] = x_offset != x_is_true_offset
                          ? static_cast<T>(0)
                          : -dy_[label_id] / x_[x_offset];
    }
  }

 private:
  T* dx_;
  const T* dy_;
  const T* x_;
  const int64_t* label_;
  size_t num_classes_;
};

template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
94
class CrossEntropyGradientOpKernel : public framework::OpKernel<T> {
Y
Yan Chunwei 已提交
95
 public:
D
dongzhihong 已提交
96
  void Compute(const framework::ExecutionContext& ctx) const override {
97 98 99 100 101
    auto* x = ctx.Input<Tensor>("X");
    auto* dy = ctx.Input<Tensor>(framework::GradVarName("Y"));
    auto* label = ctx.Input<Tensor>("Label");
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* dx_data = dx->mutable_data<T>(ctx.GetPlace());
Y
Yan Chunwei 已提交
102

103
    int64_t class_num = x->dims()[1];
104
    if (ctx.Attr<bool>("soft_label")) {
105 106 107 108 109 110 111
      XeSoftlabelGradFunctor<T> functor(dx_data, dy->data<T>(), x->data<T>(),
                                        label->data<T>(),
                                        static_cast<size_t>(class_num));
      platform::ForRange<DeviceContext> for_range(
          ctx.template device_context<DeviceContext>(),
          static_cast<size_t>(dx->numel()));
      for_range(functor);
112
    } else {
113 114 115 116 117 118 119
      XeGradFunctor<T> functor(dx_data, dy->data<T>(), x->data<T>(),
                               label->data<int64_t>(),
                               static_cast<size_t>(class_num));
      platform::ForRange<DeviceContext> for_range(
          ctx.template device_context<DeviceContext>(),
          static_cast<size_t>(dy->numel()));
      for_range(functor);
Q
Qiao Longfei 已提交
120 121 122 123 124 125
    }
  }
};

}  // namespace operators
}  // namespace paddle