cross_entropy.cc 4.5 KB
Newer Older
1
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14

15
#include "paddle/phi/kernels/funcs/cross_entropy.h"
16

17
#include "paddle/phi/backends/cpu/cpu_context.h"
18
#include "paddle/phi/core/utils/data_type.h"
19

20 21
namespace phi {
namespace funcs {
22

23
using Tensor = phi::DenseTensor;
24 25
template <typename T,
          int MajorType = Eigen::RowMajor,
26
          typename IndexType = Eigen::DenseIndex>
27
using EigenMatrix = phi::EigenMatrix<T, MajorType, IndexType>;
28

29 30
template <typename T>
struct HardLabelCrossEntropyCPUFunctorImpl {
31 32 33
  HardLabelCrossEntropyCPUFunctorImpl(phi::DenseTensor* out,
                                      const phi::DenseTensor* prob,
                                      const phi::DenseTensor* labels,
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
                                      const int ignore_index,
                                      const int axis_dim)
      : out_(out),
        prob_(prob),
        labels_(labels),
        ignore_index_(ignore_index),
        axis_dim_(axis_dim) {}

  template <typename U>
  void apply() const {
    const int batch_size = prob_->dims()[0];
    const int num_classes = prob_->dims()[1];
    const int num_remain = num_classes / axis_dim_;

    const T* prob_data = prob_->template data<T>();
    T* loss_data = out_->template data<T>();

    const auto* label_data = labels_->template data<U>();
    for (int i = 0; i < batch_size; ++i) {
      for (int j = 0; j < num_remain; j++) {
Z
Zhenghai Zhang 已提交
54
        int lbl = static_cast<int>(label_data[i * num_remain + j]);  // NOLINT
55
        if (lbl != ignore_index_) {
56 57 58 59 60 61 62
          PADDLE_ENFORCE_GE(
              lbl,
              0,
              phi::errors::OutOfRange("label value should >= 0 when label "
                                      "value(%f) not equal to ignore_index(%f)",
                                      lbl,
                                      ignore_index_));
63
          PADDLE_ENFORCE_LT(
64 65
              lbl,
              axis_dim_,
66
              phi::errors::OutOfRange(
67 68 69 70
                  "label value should less than the shape of axis dimension "
                  "when label value(%f) not equal to ignore_index(%f), But "
                  "received label value as %ld and shape of axis dimension "
                  "is %d",
71 72 73 74
                  lbl,
                  ignore_index_,
                  lbl,
                  axis_dim_));
75 76 77 78 79 80
        }
        int index = i * num_classes + lbl * num_remain + j;
        int loss_idx = i * num_remain + j;
        loss_data[loss_idx] =
            lbl == ignore_index_
                ? 0
81
                : -phi::funcs::TolerableValue<T>()(std::log(prob_data[index]));
82 83 84 85 86
      }
    }
  }

 private:
87 88 89
  phi::DenseTensor* out_;
  const phi::DenseTensor* prob_;
  const phi::DenseTensor* labels_;
90 91 92 93
  const int ignore_index_;
  const int axis_dim_;
};

94 95
template <typename DeviceContext, typename T>
void CrossEntropyFunctor<DeviceContext, T>::operator()(
96
    const DeviceContext& ctx,
97 98 99
    phi::DenseTensor* out,
    const phi::DenseTensor* prob,
    const phi::DenseTensor* labels,
100 101 102
    const bool softLabel,
    const int ignore_index,
    const int axis_dim) {
103
  if (softLabel) {
104 105
    const int batch_size = static_cast<const int>(prob->dims()[0]);
    const int num_classes = static_cast<const int>(prob->dims()[1]);
106 107 108 109 110 111 112 113
    const int num_remain = num_classes / axis_dim;

    Eigen::DSizes<int, 3> batch_axis_remain(batch_size, axis_dim, num_remain);
    auto in = EigenMatrix<T>::From(*prob);
    auto lbl = EigenMatrix<T>::From(*labels);
    auto loss = EigenMatrix<T>::From(*out);

    loss.device(*ctx.eigen_device()) =
114
        -((lbl * in.log().unaryExpr(phi::funcs::TolerableValue<T>()))
115 116 117
              .reshape(batch_axis_remain)
              .sum(Eigen::DSizes<int, 1>(1)));
  } else {
118 119
    HardLabelCrossEntropyCPUFunctorImpl<T> functor_impl(
        out, prob, labels, ignore_index, axis_dim);
120
    phi::VisitDataType(labels->dtype(), functor_impl);
121
  }
122
}
123

124 125
template class CrossEntropyFunctor<phi::CPUContext, float>;
template class CrossEntropyFunctor<phi::CPUContext, double>;
126 127 128

}  // namespace funcs
}  // namespace phi