hierarchical_sigmoid_op.h 4.8 KB
Newer Older
Y
Yancey1989 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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/framework/op_registry.h"
Y
Yancey1989 已提交
17
#include "paddle/operators/math/math_function.h"
Y
Yancey1989 已提交
18 19 20 21 22
#include "paddle/operators/math/matrix_bit_code.h"

namespace paddle {
namespace operators {

Y
Yancey1989 已提交
23 24 25 26 27
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

template <typename Place, typename T>
Y
Yancey1989 已提交
28 29
class HierarchicalSigmoidOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
30
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
31 32
    auto* in = ctx.Input<framework::Tensor>("X");
    auto* param = ctx.Input<framework::Tensor>("Parameter");
Y
Yancey1989 已提交
33 34
    auto* label = ctx.Input<framework::Tensor>("Label");
    auto* bias = ctx.Input<framework::Tensor>("Bias");
Y
Yancey1989 已提交
35
    auto* out = ctx.Output<framework::Tensor>("Out");
Y
Yancey1989 已提交
36
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
Y
Yancey1989 已提交
37 38 39 40 41 42 43 44 45

    framework::Tensor sum;
    framework::Tensor pre_out;
    auto place = ctx.GetEigenDevice<Place>();
    auto& device_ctx = ctx.device_context();
    math::ColwiseSum<Place, T> col_sum;
    math::RowwiseSum<Place, T> row_sum;

    auto pre_out_mat = EigenMatrix<T>::From(pre_out);
Y
Yancey1989 已提交
46
    int64_t batch_size = ins[0]->dims()[0];
Y
Yancey1989 已提交
47
    int64_t code_length = math::FindLastSet(num_classes - 1);
Y
Yancey1989 已提交
48

Y
Yancey1989 已提交
49
    std::vector<int64_t> pre_out_dims({batch_size, code_length});
Y
Yancey1989 已提交
50
    pre_out.mutable_data<T>(framework::make_ddim(pre_out_dims), ctx.GetPlace());
Y
Yancey1989 已提交
51 52 53
    std::vector<int64_t> sum_dims({batch_size, 1UL});
    sum.mutable_data<T>(framework::make_ddim(sum_dims), ctx.GetPlace());
    out->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
54

Y
Yancey1989 已提交
55
    if (bias) {
Y
Yancey1989 已提交
56 57
      math::AddByBitCode<T>(num_classes, *label, pre_out, *bias);
    }
Y
Yancey1989 已提交
58

Y
Yancey1989 已提交
59 60 61
    for (size_t i = 0; i < in.dims()[0]; ++i) {
      math::MulByBitCode<T>(num_classes, *label, pre_out,
                            *params->Slice(i, i + 1), *in->Slice(i, i + 1));
Y
Yancey1989 已提交
62 63 64 65 66 67
    }
    // clip the matrix with (-40, 40)
    pre_out_mat.device(place) =
        pre_out_mat.abs().cwiseMax(static_cast<T>(40.0));
    math::SumByBitCode<T>(num_classes, *label, *out, pre_out,
                          static_cast<T>(-1));
Y
Yancey1989 已提交
68 69 70 71 72

    // softrelu with threshold is 40.0
    pre_out_mat.device(place) =
        pre_out_mat.abs().cwiseMax(static_cast<T>(40.0));
    pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
Y
Yancey1989 已提交
73 74 75

    row_sum(device_ctx, pre_out, &sum);
    col_sum(device_ctx, *out, &sum);
Y
Yancey1989 已提交
76
  }
Y
Yancey1989 已提交
77 78 79 80 81
};

template <typename Place, typename T>
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
82
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
83 84 85 86
    auto* in = ctx.Input<framework::Tensor>("X");
    auto* in_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    auto* params =
        ctx.Output<framework::Tensor>(framework::GradVarName("Parameters"));
Y
Yancey1989 已提交
87 88 89 90 91 92 93 94
    auto* bias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
    auto* label =
        ctx.Output<framework::Tensor>(framework::GradVarName("Label"));
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));

    framework::Tensor pre_out;
    auto place = ctx.GetEigenDevice<Place>();
    auto& dev_ctx = ctx.device_context();
Y
Yancey1989 已提交
95
    int64_t batch_size = in_grad.dims()[0];
Y
Yancey1989 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    int64_t code_length = math::FindLastSet(num_classes - 1);
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);

    // init pre_out matrix with {1.0}
    std::vector<int64_t> pre_out_dims({batch_size, code_length});
    pre_out.mutable_data<T>(framework::make_ddim(pre_out_dims), ctx.GetPlace());
    math::SetConstant<Place, T> set;
    set(dev_ctx, &pre_out, static_cast<T>(1.0));
    // softrelu derivative
    pre_out_mat.device(place) =
        pre_out_mat * (static_cast<T>(1.0) - static_cast<T>(1.0) / pre_out_mat);

    math::SubByBitCode<T>(num_classes, *label, pre_out);

    if (bias) {
      math::AddByBitCodeGrad<T>(num_classes, *label, pre_out, *bias);
    }

Y
Yancey1989 已提交
114
    for (size_t i = 0; i < in_grad.dims()[0]; ++i) {
Y
Yancey1989 已提交
115
      math::MulByBitCodeGradWeight<T>(num_classes, *label, pre_out, *params[i],
Y
Yancey1989 已提交
116
                                      *in[i]->Slice(i, i + 1));
Y
Yancey1989 已提交
117
      math::MulByBitCodeGradError<T>(num_classes, *label, pre_out, *params[i],
Y
Yancey1989 已提交
118
                                     *ins_grad[i]->Slice(i, i + 1));
Y
Yancey1989 已提交
119 120
    }
  }
Y
Yancey1989 已提交
121 122 123 124
};

}  // namespace operators
}  // namespace paddle