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 31
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto ins = ctx.MultiInput<framework::Tensor>("X");
Y
Yancey1989 已提交
32
    auto params = ctx.MultiInput<framework::Tensor>("Parameters");
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 59 60 61 62 63 64 65 66

    for (size_t i = 0; i < ins.size(); ++i) {
      math::MulByBitCode<T>(num_classes, *label, pre_out, *params[i], *ins[i]);
    }
    // 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 已提交
67 68 69 70 71

    // 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 已提交
72 73 74

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

template <typename Place, typename T>
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto ins = ctx.MultiInput<framework::Tensor>("X");
    auto ins_grad =
        ctx.MultiOutput<framework::Tensor>(framework::GradVarName("X"));
    auto params = ctx.MultiOutput<framework::Tensor>(
        framework::GradVarName("Parameters"));
    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();
    int64_t batch_size = ins_grad.size();
    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);
    }

    for (size_t i = 0; i < ins_grad.size(); ++i) {
      math::MulByBitCodeGradWeight<T>(num_classes, *label, pre_out, *params[i],
                                      *ins[i]);
      math::MulByBitCodeGradError<T>(num_classes, *label, pre_out, *params[i],
                                     *ins_grad[i]);
    }
  }
Y
Yancey1989 已提交
121 122 123 124
};

}  // namespace operators
}  // namespace paddle