bpr_loss_op.h 4.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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 "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/for_range.h"
19
#include "paddle/phi/core/tensor_utils.h"
20
#include "paddle/phi/kernels/funcs/math_function.h"
21 22 23 24

namespace paddle {
namespace operators {

F
frankwhzhang 已提交
25 26 27
/*Todo:
 *Find a way to adapt TolerableValue, using blas or eigen.
 */
28 29 30 31 32 33 34 35 36 37
template <typename T>
struct TolerableValue {
  HOSTDEVICE T operator()(const T& x) const {
    const T kApproInf = 1e20;
    if (x == INFINITY) return kApproInf;
    if (x == -INFINITY) return -kApproInf;
    return x;
  }
};

38
template <typename T, typename DeviceContext>
39 40 41
class BprLossOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
42 43 44
    auto* x = ctx.Input<phi::DenseTensor>("X");
    auto* label = ctx.Input<phi::DenseTensor>("Label");
    auto* y = ctx.Output<phi::DenseTensor>("Y");
45 46 47
    y->mutable_data<T>(ctx.GetPlace());
    int rank = x->dims().size();

48 49 50
    phi::DenseTensor x_2d = phi::ReshapeToMatrix(*x, rank - 1);
    phi::DenseTensor labels_2d = phi::ReshapeToMatrix(*label, rank - 1);
    phi::DenseTensor y_2d = phi::ReshapeToMatrix(*y, rank - 1);
51

52 53 54
    const phi::DenseTensor* logits = &x_2d;
    const phi::DenseTensor* labels = &labels_2d;
    phi::DenseTensor* out = &y_2d;
55

56 57 58
    const int step_size = logits->dims()[0];
    const int class_num = logits->dims()[1];
    const T* logits_data = logits->data<T>();
59 60
    T* loss_data = out->data<T>();

61
    const int64_t* label_data = labels->data<int64_t>();
62
    for (int i = 0; i < step_size; ++i) {
63
      int lbl_pos = label_data[i];
64 65
      PADDLE_ENFORCE_GE(lbl_pos,
                        0,
66 67
                        platform::errors::InvalidArgument(
                            "label data %d is illegal.", lbl_pos));
68 69
      PADDLE_ENFORCE_LT(lbl_pos,
                        class_num,
70 71
                        platform::errors::InvalidArgument(
                            "label data %d is illegal.", lbl_pos));
72 73 74 75 76 77
      int index_pos = i * class_num + lbl_pos;
      T sum = static_cast<T>(0);
      for (int j = 0; j < class_num; j++) {
        if (j == lbl_pos) continue;
        int index_neg = i * class_num + j;
        sum += TolerableValue<T>()(-std::log(
78 79
            1.0f + TolerableValue<T>()(std::exp(logits_data[index_neg] -
                                                logits_data[index_pos]))));
80 81 82 83 84 85
      }
      loss_data[i] = -sum / (class_num - 1);
    }
  }
};

86
template <typename T, typename DeviceContext>
87 88 89
class BprLossGradientOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
90 91 92 93
    auto* x = ctx.Input<phi::DenseTensor>("X");
    auto* dy = ctx.Input<phi::DenseTensor>(framework::GradVarName("Y"));
    auto* label = ctx.Input<phi::DenseTensor>("Label");
    auto* dx = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
94

95 96
    const size_t step_size = static_cast<size_t>(x->dims()[0]);
    const size_t num_classes = static_cast<size_t>(x->dims()[1]);
F
frankwhzhang 已提交
97 98 99
    T* dx_data = dx->mutable_data<T>(ctx.GetPlace());
    const T* dy_data = dy->data<T>();
    const T* x_data = x->data<T>();
100
    const int64_t* label_data = label->data<int64_t>();
101 102

    for (size_t sample_id = 0; sample_id < step_size; sample_id++) {
F
frankwhzhang 已提交
103
      for (size_t x_offset = sample_id * num_classes;
104 105
           x_offset < (sample_id + 1) * num_classes;
           x_offset++) {
F
frankwhzhang 已提交
106
        dx_data[x_offset] = static_cast<T>(0);
107
      }
108
      auto p_index = sample_id * num_classes + label_data[sample_id];
F
frankwhzhang 已提交
109
      for (size_t ni = 0; ni < num_classes; ni++) {
110
        if (label_data[sample_id] == static_cast<int>(ni)) continue;
F
frankwhzhang 已提交
111 112 113 114 115 116 117
        auto n_index = sample_id * num_classes + ni;
        auto grad_ = -dy_data[sample_id] /
                     ((num_classes - 1) *
                      (1.0f + TolerableValue<T>()(std::exp(x_data[p_index] -
                                                           x_data[n_index]))));
        dx_data[p_index] += grad_;
        dx_data[n_index] -= grad_;
118 119
      }
    }
120 121 122 123 124
  }
};

}  // namespace operators
}  // namespace paddle