hsigmoid_loss_kernel.cc 4.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2022 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.

15
#include "paddle/phi/kernels/hsigmoid_loss_kernel.h"
16 17

#include "paddle/phi/backends/cpu/cpu_context.h"
18
#include "paddle/phi/common/transform.h"
19 20 21 22
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/eigen/eigen_function.h"
#include "paddle/phi/kernels/funcs/math_function_impl.h"
23
#include "paddle/phi/kernels/funcs/matrix_bit_code.h"
W
wuyefeilin 已提交
24
#include "paddle/phi/kernels/impl/clip_kernel_impl.h"
25 26 27 28

namespace phi {

template <typename T, typename Context>
29 30 31
void HSigmoidLossKernel(const Context& ctx,
                        const DenseTensor& x,
                        const DenseTensor& label,
32 33
                        const DenseTensor& w,
                        const paddle::optional<DenseTensor>& bias,
34 35 36 37 38 39 40 41
                        const paddle::optional<DenseTensor>& path,
                        const paddle::optional<DenseTensor>& code,
                        int num_classes,
                        bool remote_prefetch,
                        bool is_sparse,
                        DenseTensor* out,
                        DenseTensor* pre_out,
                        DenseTensor* w_out) {
42 43 44 45 46 47 48
  size_t num_classes_st = static_cast<size_t>(num_classes);
  // for remote prefetch

  bool is_custom = false;
  if (path.get_ptr()) {
    is_custom = true;
  }
49 50 51
  int64_t code_length = path.get_ptr()
                            ? path.get_ptr()->dims()[1]
                            : phi::funcs::FindLastSet(num_classes_st - 1);
52 53 54 55 56 57 58 59 60 61 62 63 64
  int64_t batch_size = x.dims()[0];
  DenseTensor sum;
  pre_out->Resize(phi::make_ddim({batch_size, code_length}));
  ctx.template Alloc<T>(pre_out);
  auto* pre_out_data = pre_out->data<T>();
  auto pre_out_mat = EigenMatrix<T>::From(*pre_out);
  // Not all class(leaf) nodes' path lengths equal code_length, thus init as
  // 0s can avoid out of path's loss.
  funcs::SetConstant<Context, T> zero;
  zero(ctx, pre_out, static_cast<T>(0.0));
  auto& place = *ctx.eigen_device();
  funcs::RowwiseSum<Context, T> row_sum;

65
  std::unique_ptr<phi::funcs::MatrixBitCodeFunctor<T>> bit_code;
66
  if (!is_custom) {
67
    bit_code.reset(new phi::funcs::MatrixBitCodeFunctor<T>(
68 69
        num_classes_st, label.template data<int64_t>()));
  } else {
70
    bit_code.reset(new phi::funcs::MatrixBitCodeFunctor<T>(
71 72 73 74 75 76 77 78 79 80 81 82 83 84
        *(path.get_ptr()), *(code.get_ptr()), label.template data<int64_t>()));
  }

  std::vector<int64_t> sum_dims({batch_size, 1UL});
  sum.Resize(phi::make_ddim(sum_dims));
  ctx.template Alloc<T>(&sum);
  auto sum_mat = EigenMatrix<T>::From(sum);
  ctx.template Alloc<T>(out);
  auto out_mat = EigenMatrix<T>::From(*out);
  if (bias.get_ptr()) {
    bit_code->Add(*(bias.get_ptr()), pre_out);
  }
  bit_code->Mul(pre_out, w, x);
  // clip to [-40, 40]
85
  phi::Transform<Context> trans;
86 87 88 89
  trans(ctx,
        pre_out_data,
        pre_out_data + pre_out->numel(),
        pre_out_data,
W
wuyefeilin 已提交
90
        ClipFunctor<T>(static_cast<T>(-40.0), static_cast<T>(40.0)));
91 92 93 94 95 96 97 98 99 100 101 102 103
  bit_code->Sum(*pre_out, out, static_cast<T>(-1));
  // use softrelu to calculate cross entropy
  pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
  row_sum(ctx, *pre_out, &sum);
  // TODO(guosheng): Subtract the out of path's loss, since not all
  // class(leaf) nodes' path lengths equal code_length. But it won't break the
  // gradient check since both have the out of path's loss and will cancel out
  // each other.
  out_mat.device(place) = sum_mat + out_mat;
}

}  // namespace phi

104 105
PD_REGISTER_KERNEL(
    hsigmoid_loss, CPU, ALL_LAYOUT, phi::HSigmoidLossKernel, float, double) {}