center_loss_op.h 5.7 KB
Newer Older
H
HaoRen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*Copyright (c) 2019 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 <algorithm>
#include <cstring>
#include <limits>
#include <vector>
20

H
HaoRen 已提交
21 22
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
23
#include "paddle/phi/common/transform.h"
24
#include "paddle/phi/kernels/funcs/blas/blas.h"
25

H
HaoRen 已提交
26 27 28
namespace paddle {
namespace operators {

29 30
template <typename T,
          int MajorType = Eigen::RowMajor,
H
HaoRen 已提交
31 32
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;
33 34
template <typename T,
          int MajorType = Eigen::RowMajor,
H
HaoRen 已提交
35 36 37 38 39 40 41 42 43 44 45 46
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

template <typename T>
struct SubFunctor {
  inline HOSTDEVICE T operator()(T a, T b) const { return a - b; }
};

template <typename DeviceContext, typename T>
class CenterLossKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
47 48 49 50
    auto *X = ctx.Input<phi::DenseTensor>("X");  // deep feature
    auto *labels = ctx.Input<phi::DenseTensor>("Label");
    auto *centers = ctx.Input<phi::DenseTensor>("Centers");
    auto *update_rate = ctx.Input<phi::DenseTensor>("CenterUpdateRate");
H
HaoRen 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    int cluster_num = ctx.Attr<int>("cluster_num");
    auto *lr_center = update_rate->data<T>();
    T alpha = lr_center[0];
    bool need_update = static_cast<T>(ctx.Attr<bool>("need_update"));

    auto x_data = X->data<T>();
    auto label_data = labels->data<int64_t>();

    auto centers_dim = centers->dims();
    auto centers_data = centers->data<T>();

    auto x_dims = X->dims();
    int batch_size = x_dims[0];
    int deep_feat_dim = x_dims[1];

66
    auto centers_diff = ctx.Output<phi::DenseTensor>("SampleCenterDiff");
H
HaoRen 已提交
67
    auto centers_diff_data = centers_diff->mutable_data<T>(ctx.GetPlace());
68
    auto *out_loss = ctx.Output<phi::DenseTensor>("Loss");
H
HaoRen 已提交
69

70
    auto *centers_out = ctx.Output<phi::DenseTensor>("CentersOut");
H
HaoRen 已提交
71 72 73 74 75 76 77 78 79 80 81 82
    auto *centers_out_data = centers_out->mutable_data<T>(ctx.GetPlace());

    if (centers_out_data != centers_data) {
      int size = centers_out->numel() * sizeof(T);
      memcpy(centers_out_data, centers_data, size);
    }

    std::vector<int> center_update_count(cluster_num, 1);
    auto &dev_ctx = ctx.template device_context<DeviceContext>();

    auto loss_data = out_loss->mutable_data<T>(ctx.GetPlace());

83
    phi::DenseTensor centers_diffacc;  // used to accumulate all diff
H
HaoRen 已提交
84 85 86 87 88
    auto centers_diffacc_data =
        centers_diffacc.mutable_data<T>(centers_dim, ctx.GetPlace());
    int numel = centers_diffacc.numel();
    std::memset(centers_diffacc_data, 0, sizeof(T) * numel);

89
    auto blas = phi::funcs::GetBlas<DeviceContext, T>(ctx);
H
HaoRen 已提交
90 91 92 93 94 95 96
    int tLabel;

    const T *x_index;
    const T *center_index;
    T *center_out_index;
    T *center_loss_diff_index;
    T *acc_index;
97
    phi::Transform<DeviceContext> trans;
H
HaoRen 已提交
98 99 100 101 102 103 104

    for (int i = 0; i < batch_size; ++i) {
      tLabel = label_data[i];
      center_update_count[tLabel]++;
      x_index = x_data + i * deep_feat_dim;                  // xi index
      center_index = centers_data + tLabel * deep_feat_dim;  // center index
      center_loss_diff_index = centers_diff_data + i * deep_feat_dim;
105 106 107 108 109 110
      trans(dev_ctx,
            x_index,
            x_index + deep_feat_dim,
            center_index,
            center_loss_diff_index,
            SubFunctor<T>());
H
HaoRen 已提交
111 112

      acc_index = centers_diffacc_data + tLabel * deep_feat_dim;
113 114 115
      blas.VADD(deep_feat_dim,
                center_loss_diff_index,
                acc_index,
H
HaoRen 已提交
116
                acc_index);  // accumulate
117 118 119 120
      loss_data[i] =
          blas.DOT(
              deep_feat_dim, center_loss_diff_index, center_loss_diff_index) /
          T(2.0);
H
HaoRen 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }

    // update centers data
    if (need_update == true) {
      for (int i = 0; i < cluster_num; i++) {
        acc_index = centers_diffacc_data + i * deep_feat_dim;
        center_out_index = centers_out_data + i * deep_feat_dim;
        T scale = alpha / center_update_count[i];
        blas.SCAL(deep_feat_dim, scale, acc_index);
        blas.VADD(deep_feat_dim, acc_index, center_out_index, center_out_index);
      }
    }
  }
};

template <typename DeviceContext, typename T>
class CenterLossGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
140 141 142
    auto *in0 = context.Input<phi::DenseTensor>("SampleCenterDiff");
    auto *in1 = context.Input<phi::DenseTensor>(framework::GradVarName("Loss"));
    auto *x_g = context.Output<phi::DenseTensor>(framework::GradVarName("X"));
H
HaoRen 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156
    auto sub_result = EigenMatrix<T>::From(*in0);
    auto out_grad = EigenMatrix<T>::From(*in1);

    auto x_dims = x_g->dims();
    int cols = x_g->numel() / x_dims[0];
    // calculate gradient
    auto grad_mat =
        (out_grad.broadcast(Eigen::array<int, 2>({{1, cols}}))) * sub_result;

    // propagate back to input
    auto &eigen_place =
        *context.template device_context<DeviceContext>().eigen_device();
    x_g->mutable_data<T>(context.GetPlace());
    // eigen matrix
157
    auto x_grad = EigenMatrix<T>::From(*x_g, phi::make_ddim({x_dims[0], cols}));
H
HaoRen 已提交
158 159 160 161 162 163
    x_grad.device(eigen_place) = grad_mat;
  }
};

}  // namespace operators
}  // namespace paddle